您的位置:首页 > 其它

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
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: