您的位置:首页 > 其它

LeetCode题解:Binary Tree Postorder Traversal

2013-11-10 05:10 323 查看

Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example:

Given binary tree
{1,#,2,3}
,

1
\
2
/
3

return
[3,2,1]
.

Note: Recursive solution is trivial, could you do it iteratively?

思路:

无难度。

题解:

/**
* 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<int> postorderTraversal(TreeNode *root) {
vector<int> ret;

if (root == nullptr)
return ret;

list<pair<TreeNode*, bool>> traverse;
traverse.push_back(make_pair(root, false));
while(!traverse.empty())
{
auto& front = traverse.front();
if (front.second)
{
// second time visit it
ret.push_back(front.first->val);
traverse.pop_front();
}
else
{
// first time visit it
front.second = true;

if (front.first->right)
traverse.push_front(make_pair(front.first->right, false));

if (front.first->left)
traverse.push_front(make_pair(front.first->left, false));
}
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: