# 面试题34

输入一棵二叉树和一个整数，打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

```
示例:
给定如下二叉树，以及目标和 sum = 22，

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]
```

## 提示：

* 节点总数 <= 10000

## 注意：本题与主站 113 题相同：<https://leetcode-cn.com/problems/path-sum-ii/>

## Solutions

1. **dfs with recursion**

```cpp
/**
 * 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:
    vector<vector<int>> res;
    vector<int> path;
    void dfs(TreeNode * root, int sum) {
        if (!root) return;
        sum -= root->val;
        path.push_back(root->val);
        if (!root->left && !root->right) {
            if (sum == 0)
                res.push_back(path);
        }
        else {
            dfs(root->left, sum);
            dfs(root->right, sum);
        }
        path.pop_back();
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        dfs(root, sum);
        return res;
    }
};
```

1. **postorder traversal with stack**

```cpp
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        stack<TreeNode *> s;
        vector<vector<int>> res;
        vector<int> path;
        TreeNode * prev = nullptr;

        while (root || !s.empty()) {
            while (root) {
                s.push(root);
                sum -= root->val;
                path.push_back(root->val);
                root = root->left;
            }
            root = s.top();
            if (root->right && root->right != prev)
                root = root->right;
            else {
                if (!root->left && !root->right)
                    if (sum == 0)
                        res.push_back(path);
                path.pop_back();
                sum += root->val;
                prev = root; root = nullptr;
                s.pop();
            }
        }

        return res;
    }
};
```


---

# 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://zhongquan789.gitbook.io/leetcode/lcof/mian-shi-ti-34.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.
