LeetCode_112. Path Sum

Posted denggelin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode_112. Path Sum相关的知识,希望对你有一定的参考价值。

 

112. Path Sum

Easy

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     /     4   8
   /   /   11  13  4
 /  \      7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

 

package leetcode.easy;

public class PathSum 
	@org.junit.Test
	public void test() 
		int sum = 22;
		TreeNode tn11 = new TreeNode(5);
		TreeNode tn21 = new TreeNode(4);
		TreeNode tn22 = new TreeNode(8);
		TreeNode tn31 = new TreeNode(11);
		TreeNode tn33 = new TreeNode(13);
		TreeNode tn34 = new TreeNode(4);
		TreeNode tn41 = new TreeNode(7);
		TreeNode tn42 = new TreeNode(2);
		TreeNode tn46 = new TreeNode(1);
		tn11.left = tn21;
		tn11.right = tn22;
		tn21.left = tn31;
		tn21.right = null;
		tn22.left = tn33;
		tn22.right = tn34;
		tn31.left = tn41;
		tn31.right = tn42;
		tn33.left = null;
		tn33.right = null;
		tn34.left = null;
		tn34.right = tn46;
		tn41.left = null;
		tn41.right = null;
		tn42.left = null;
		tn42.right = null;
		tn46.left = null;
		tn46.right = null;
		System.out.println(hasPathSum(tn11, sum));
	

	public boolean hasPathSum(TreeNode root, int sum) 
		if (null == root) 
			return false;
		 else if (null == root.left && null == root.right && 0 == sum - root.val) 
			return true;
		 else 
			return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
		
	

 

以上是关于LeetCode_112. Path Sum的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]题解(python):112 Path Sum

Java [Leetcode 112]Path Sum

LeetCode Oj 112. Path Sum 解题报告

leetcode112. Path Sum

leetcode112 Path Sum

LeetCode 112 Path Sum