版权声明:『无垢识·空之境界』 https://blog.csdn.net/ecysakura/article/details/88912848
这道题是LeetCode里的第145道题。
题目要求:
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解题代码:
/**
* Definition for a binary tree node.
* 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) {
stack<TreeNode*>st;
TreeNode *cur,*pre=NULL;
vector<int>res;
if(root==NULL)
return res;
cur=root;
st.push(cur);
while(st.size()!=0){
cur=st.top();
if((cur->left==NULL&&cur->right==NULL)||
(pre!=NULL&&(pre==cur->left||pre==cur->right))
){
res.push_back(cur->val);
st.pop();
pre=cur;
}
else{
if(cur->right!=NULL)
st.push(cur->right);
if(cur->left!=NULL)
st.push(cur->left);
}
}
return res;
}
};