二叉树的后序遍历顺序为,root->left, root->right, root,所以须要保存根节点的状态。显然使用栈来模拟递归的过程,可是难点是怎么从root->right转换到root。post
1 vector<int> postOrder(TreeNode *root) 2 { 3 vector<int> res; 4 if(root == NULL) return res; 5 6 TreeNode *p = root; 7 stack<TreeNode *> sta; 8 TreeNode *last = root; 9 sta.push(p); 10 while (!sta.empty()) 11 { 12 p = sta.top(); 13 if( (p->left == NULL && p->right == NULL) || (p->right == NULL && last == p->left) || (last == p->right) ) 14 { 15 res.push_back(p->val); 16 last = p; 17 sta.pop(); 18 } 19 else 20 { 21 if(p->right) 22 sta.push(p->right); 23 if(p->left) 24 sta.push(p->left); 25 } 26 27 } 28 29 30 return res; 31 }
方法2:
其实咱们但愿栈中保存的从顶部依次是root->left, root->right, root,当符合上面提到的条件时,就进行出栈操做。有一种巧妙的方法能够作到,先上代码
1 vector<int> postOrder(TreeNode *root) 2 { 3 vector<int> res; 4 if(root == NULL) return res; 5 6 TreeNode *p = root; 7 stack<TreeNode *> sta; 8 sta.push(p); 9 sta.push(p); 10 while(!sta.empty()) 11 { 12 p = sta.top(); sta.pop(); 13 if(!sta.empty() && p==sta.top()) 14 { 15 if(p->right) sta.push(p->right), sta.push(p->right); 16 if(p->left) sta.push(p->left), sta.push(p->left); 17 } 18 else 19 res.push_back(p->val); 20 } 21 22 return res; 23 }
对于每一个节点,都压入两遍,在循环体中,每次弹出一个节点赋给p,若是p仍然等于栈的头结点,说明p的孩子们尚未被操做过,应该把它的孩子们加入栈中,不然,访问p。也就是说,第一次弹出,将p的孩子压入栈中,第二次弹出,访问p。