# LeetCode – Path Sum  Solution
Date: 2020-07-12


### **题目：**

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.

### **实现：**

- 递归方式，DFS遍历所有路径找出符合条件的路径， sum值，每次调用时剪掉当前的值， 最后符合条件的路径中叶子节点的值与sum相同， 空间复杂度O(N)    时间复杂度 O(N)          

```

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null ){
            return false;
        }
        if (root.left == null && root.right == null && root.val == sum){
            return true;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}
```

- 迭代方式，使用栈实现先序遍历， 对于sum计算与递归模式不同，入栈前加上父节点的val， 这样如果找到符合要求的节点， 则节点val与sum值一致。     空间复杂度O(N)    时间复杂度 O(N)

```

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null){
            return false;
        }
        Stack<TreeNode> st = new Stack<TreeNode>();
        st.push(root);
        
        while (!st.empty()){
            TreeNode node = st.pop();
            if (node.left == null && node.right == null && node.val == sum){
                return true;
            }
            if (node.left != null){
                node.left.val += node.val;
                st.push(node.left);
            }
            if (node.right != null){
                node.right.val += node.val;
                st.push(node.right);
            }
        }
        return false;
    }
}
```

