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]
Follow up: Recursive solution is trivial, could you do it iteratively?
/**
* 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) {
if (root==NULL)
return vector<int> ();
TreeNode *Pcur, *Plast;
vector<int> result;
stack<TreeNode*> treestack;
Pcur = root;
Plast = NULL;
while(Pcur){
treestack.push(Pcur);
Pcur = Pcur->left;
}
while(!treestack.empty()){
Pcur = treestack.top();
treestack.pop();
//Only condition to print
if(Pcur->right==NULL||Pcur->right==Plast){
Plast = Pcur;
result.push_back(Pcur->val);
}
else{
treestack.push(Pcur);
Pcur = Pcur->right;
while(Pcur){
treestack.push(Pcur);
Pcur = Pcur->left;
}
}
}
return result;
}
};
非递归的二叉树后序遍历,要点是设置两个结点指针,一个是current结点,一个是last结点。将current结点先置于最左节点上。然后开始进行循环,判断能够输出的唯一条件是,current结点的右子树为空或者右子树是上一个被访问过的结点,也就是last结点。如果不满足条件,就重新将current结点入栈,且让current结点走到右子树的最左端,其他结点也依次入栈。