leetcode Path Sum II 关于树的后序遍历
2014-09-29 15:12
405 查看
我们利用辅助栈来进行树的后序遍历的时候可以发现栈里保留的是一条根节点到访问的节点的路径,我们可以根据这个性质来解关于树的高度,某条路径和等一系列的问题。
例:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and
return
代码如下:
例:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
代码如下:
/** * Definition for binary tree * 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; } TreeNode* p = root; stack<TreeNode*> s; TreeNode* prev = NULL; vector<int> tmp; while (p || !s.empty()) { if (p) { s.push(p); tmp.push_back(p->val); p = p->left; } else { p = s.top(); if (p->right && p->right != prev) { p = p->right; s.push(p); tmp.push_back(p->val); p = p->left; } else { if (p->left == NULL && p->right == NULL) { int total = 0; for (int i = 0; i < tmp.size(); i++) { total += tmp[i]; } if (total == sum) { result.push_back(tmp); } } s.pop(); tmp.erase(tmp.end() - 1); prev = p; p = NULL; } } } return result; } };
相关文章推荐
- [LeetCode] Path Sum II, 关于效率的两个问题: vector还是queue? 传递引用还是拷贝?
- LeetCode: Path Sum II
- functionclass[LeetCode]Path Sum II
- LeetCode_Path Sum II
- LeetCode 113: Path Sum II
- [LeetCode] Unique Paths、Unique Paths II、Minimum Path Sum
- leetcode: Path Sum II
- [LeetCode 112 113] - 路径和I & II (Path Sum I & II)
- leetcode--Path Sum II
- [leetcode]Path Sum II
- [leetcode] Path Sum II
- leetcode path sum II
- Leetcode: Path Sum II
- [Leetcode]Path Sum II
- [Leetcode] Path Sum II
- leetcode 119: Path Sum II
- [LeetCode]Path Sum II
- LeetCode: Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II 解题报告