您的位置:首页 > 编程语言 > Java开发

Path Sum (Java)

2014-12-23 22:02 106 查看
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.

For 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.

深搜到叶子的和判断与sum是否相等

Source

public boolean hasPathSum(TreeNode root, int sum) {
if( root == null){
return false;
}
if( root.left == null && root.right == null){
return sum - root.val == 0;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);		//递归应当注意的就是状态转移的这个式子,这道题是当前sum确定倒推到叶子所以用减 (通常是叶子确定 推到根用加)
}

Test

public static void main(String[] args){
TreeNode a = new TreeNode(5);
a.left = new TreeNode(4);
a.right = new TreeNode(8);
a.left.left = new TreeNode(11);
a.left.left.left = new TreeNode(7);
a.left.left.right = new TreeNode(2);
a.right.left = new TreeNode(13);
a.right.right = new TreeNode(4);
a.right.right.right = new TreeNode(1);
System.out.println(new Solution().hasPathSum(a, 22));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息