1.题目
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?
2.题意
二叉树后序遍历
3.分析
1)递归,直接按照左、右、root的顺序放进vector即可
2)借助两个栈
s1将每两个孩子节点按照左、右的顺序进栈
则每个栈顶元素出栈时再按照root、右、左的顺序进入s2
将s2所有元素出栈到vector即可得到左、右、root的后序遍历序列
4.代码
1)递归版
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
postorder(result, root);
return result;
}
private:
void postorder(vector<int> &result, TreeNode *root) {
if(root == nullptr)
return;
postorder(result, root->left);
postorder(result, root->right);
result.push_back(root->val);
}
};
2)迭代版
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == nullptr)
return result;
stack<const TreeNode*> s1;
stack<const TreeNode*> s2;
const TreeNode *p = root;
s1.push(root);
while(!s1.empty())
{
p = s1.top();
s1.pop();
s2.push(p);
if(p->left)
s1.push(p->left);
if(p->right)
s1.push(p->right);
}
while(!s2.empty())
{
p = s2.top();
s2.pop();
result.push_back(p->val);
}
return result;
}
};