/**
* 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> ans;
stack<TreeNode*> rootStack;
stack<int> rStack;
while(true){
cout<<rootStack.size()<<endl;
if(root!=NULL){
if(root->left!=NULL){
//进栈条件是左右中成立,遍历到左子树之前
rootStack.push(root);
rStack.push((root->right==NULL)?0:1);
root=root->left;
}
else if(root->right!=NULL){
//遍历到右子树时,左子树已经清空
rootStack.push(root);
rStack.push(0);
root=root->right;
}
else{
ans.push_back(root->val);
root=NULL;
}
}
else if(!rootStack.empty()){
root=rootStack.top();
if(rStack.top()==1){
//该节点仍未遍历右结点
rStack.top()=0;
root=root->right;
}
else{
//该结点已遍历到其本身
root->left=NULL;
root->right=NULL;
rootStack.pop();
rStack.pop();
}
}
else
break;
}
return ans;
}
};
利用了剪枝思想