DataStructure_Algorithm_HandBook_PreForLeetCode

112. Path Sum

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

img

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

img

Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

Example 3:

Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

Constraints:

solution

这道题之前的路径之和很像,现在是判断路径是否等于某个特定值,我们可以用 dfs,然后每遍历一个点,减去其节点的 val,在减之前,每次判断是否等于其本身的值且是否为叶子节点,如果是就直接返回 true,不是就继续遍历,如果遍历完还没有就返回 false

注意这里的 example 3, 即使root 为空,targetsum 也为空,还是返回 false

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
              return  dfs(root,targetSum);
    }
    boolean dfs(TreeNode node,int target_sum){
        if(node == null) return false;
        if(node.left == null && node.right == null){
          return target_sum == node.val;
        }
        return dfs(node.left,target_sum - node.val) ||  dfs(node.right,target_sum  - node.val);
    }
}

DFS 的思路也类似,但是我们可以用一个叠加的方式来考虑,遍历过一个节点就加上上一层父结点的值,如果刚好遍历到叶子节点,然后值又和 target 相等,就 return true。

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        Deque<TreeNode> q= new LinkedList();
        if(root != null ) q.offer(root);
        while(!q.isEmpty()){
            int size = q.size();
            for (int i = 0; i< size; i++){
                TreeNode node = q.poll();
                if(node.left == null && node.right == null && node.val == targetSum) return true;
                if(node.left!= null) {
                    node.left.val+=node.val;
                    q.offer(node.left);
                    }
                if(node.right!= null){
                    node.right.val+=node.val;
                    q.offer(node.right);
                    }
            }
        }
        return false;
}
}