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;
}
};