# Path Sum

<https://leetcode.com/problems/path-sum/description/>

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

## Thoughts

先想分治。从当前结点到叶有sum的path意味着它的左/右结点到叶有sum-node.val的path。

Errors:\
1\. node == null代表父节点是叶节点。

## Code

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }

        if (root.val == sum && root.left == null && root.right == null) {
            return true;
        }

        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}
```

## Analysis

一次分治遍历O(n).

## Ver.2

因为要区分不同的path， iterative 版本inorder traversal能很好的记录path信息. 当退回到中间节点时, 不能直接pop, 否则path将不再包含它, 而是要检查它的右子树是否存在, 并把右子树pushLeft. 但如果每次都pushLeft则无法正常让中间节点退出, 因此还要把上个退出的节点记下来, 看是否和中间节点的right一致, 当一致时意味着右子树已经查过了, 不需要再pushLeft了.

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        stack<TreeNode*> s;
        int psum = 0;
        const auto push_left = [&](TreeNode *cur) {
            while (cur != NULL) {
                psum += cur->val;
                s.push(cur);
                cur = cur->left;
            }
        };
        push_left(root);
        TreeNode *pre = NULL;
        while (!s.empty()) {
            const auto cur = s.top();
            if (cur->left == NULL && cur->right == NULL && psum == sum) return true;
            if (cur->right != NULL && cur->right != pre) {
                push_left(cur->right);
                continue;
            }
            s.pop();
            pre = cur;
            psum -= cur->val;
        }
        return false;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/binary_tree_and_divide_conquer/divide-and-concquer/path-sum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
