题目:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
题意:后序不让用递归遍历二叉树
思路:先root进站,取栈顶
1,一直找到最左的子节点,边找边进站,成为新的栈顶
2.判断栈顶的右子节点有没有被访问
3.如果没有,取右子节点,重复1的工作
4,如果有,按照后序遍历,既然右边都被访问了,那么肯定左边在右边之前被访问了,那么就可以访问本身节点了,然后向上走一级,把刚才访问的节点当成上一级的右子 节点
代码:
/**
* 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*> stack1;
vector <int> result;
bool visited;
TreeNode *p = root,*q;
if(!root) return result;
do{
while(p!=NULL){
stack1.push(p);
p = p->left;
}
visited = true;
q = NULL;
while(!stack1.empty() && visited){
p = stack1.top();
if(p ->right ==q){
result.push_back(p->val);
stack1.pop();
q = p;
}
else{
p = p->right;
visited =false;
}
}
}while(!stack1.empty());
return result;
}
};