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);
		}
	}
}

 

Guess you like

Origin www.cnblogs.com/denggelin/p/11619789.html