题目描述
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) {
if(root==NULL)
return vector<int>{};
vector<int> res;
stack<TreeNode*> frontsta;
stack<TreeNode*> backsta;
frontsta.push(root);
while(!frontsta.empty())
{
TreeNode* temp=frontsta.top();
backsta.push(temp);
frontsta.pop();
if(temp->left)
frontsta.push(temp->left);
if(temp->right)
frontsta.push(temp->right);
}
while(!backsta.empty())
{
res.push_back(backsta.top()->val);
backsta.pop();
}
return res;
}
};