Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
题解:用非递归方式给出二叉树的后序遍历序列,正常想法直接用个栈但是后序是L-R-root的顺序,用栈push时必须先把Rpush进来再pushL,因为最先弹出的是L,之后要判断的就是得到栈中的top节点要怎么判断此时操作是继续push还是pop就是关键,如果是叶节点直接push,但是如果不是叶节点呢,此时如果不是叶节点那么其左右节点肯定已经访问过,可以设置一个set数组记录是否访问过,实际上这道题就是再得到top节点后,看成一个root,因为后序遍历root是最后的,所以如果你要进行pop操作,左右节点要么为空要么都是访问过的
100%代码:
/**
* 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) {
vector<int> op;
stack<TreeNode*> st;
if(root == nullptr) return op;
unordered_set<TreeNode*> vis;
st.push(root);
while(!st.empty()){
TreeNode* cur=st.top();
if((vis.find(cur->left)!=vis.end()||!cur->left)&&(vis.find(cur->right)!=vis.end()||!cur->right))
{
op.push_back(cur->val);
st.pop();
vis.insert(cur);
}else{
if(cur->right) st.push(cur->right);
if(cur->left) st.push(cur->left);
}
}
return op;
}
};