LeetCode 113
Path Sum II
Problem Description:
给出一棵二叉树,遍历输出二叉树中从根节点到叶节点的所有节点和等于题目给出的定值sum的所有路径。
具体的题目信息:
https://leetcode.com/problems/path-sum-ii/description/- Example:
- Solution:
- 解题思路:
通过二叉树的非递归后序遍历实现,用vector
同步记录stack
中节点对应的值。注意!虽然二者同步,但是在while
循环判断语句那里也要对二者都进行判断,不然会出现unknown error。 - 编程实现:
- 解题思路:
/**
* 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>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> result;
if (root == NULL) return result;
int SUM = 0;
stack<TreeNode*> node;
vector<int> path;
TreeNode* cur = root;
TreeNode* pre = NULL;
while(cur || !node.empty() || !path.empty()) {
while(cur) {
node.push(cur);
path.push_back(cur->val);
SUM += cur->val;
cur = cur->left;
}
cur = node.top();
if (cur->left == NULL && cur->right == NULL && SUM == sum) {
result.push_back(path);
}
if (cur->right && cur->right != pre) {
cur = cur->right;
} else {
pre = cur;
node.pop();
path.pop_back();
SUM -= cur->val;
cur = NULL;
}
}
return result;
}
};