右子树的处理:
(1)先处理左孩子。
(2) 判断右孩子是否访问。Yes,访问根;NO,入栈右孩子及其全部左孩子。
<span style="font-size:14px;">/**
* 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) {
stack<TreeNode *> stack;
vector<int> res;
if(root==NULL) return res;
TreeNode * tmp =root;
TreeNode * visited=NULL;
stack.push(tmp);
//input all the left nodes
while(tmp->left!=NULL){
stack.push(tmp->left);
tmp = tmp->left;
}
//process the right branch
while(!stack.empty()){
tmp=stack.top();
if(tmp->right == visited || tmp->right==NULL){//left&right visited, then visit root
stack.pop();
res.push_back(tmp->val);
visited = tmp;
}
else{//if right child is not null, stack itself and all its left child
tmp=tmp->right;
stack.push(tmp);
while(tmp->left!=NULL){
stack.push(tmp->left);
tmp = tmp->left;
}
}
}
return res;
}
};</span>