112 Path Sum

112. Path Sum

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值,如果左子树是空的,但是右子树不空,就不能算作答案,所以在辅助函数里面还要检查。

    public boolean hasPathSum(TreeNode root, int sum) {
        return helper(root, sum);
    }

    private boolean helper(TreeNode root, int target) {
        if(root == null) {
            return false;
        }
        if(root.left == null && root.right == null) {
            return root.val == target;
        }
        return helper(root.left, target - root.val) || helper(root.right, target - root.val);
    }

results matching ""

    No results matching ""