LeetCode145. 二叉树的后序遍历

题目

分析

后序遍历的非递归写法基本上就是按照前序遍历的非递归写出来的。前序遍历:根左右,后序遍历:左右根。如果把前序遍历的结果反转:得到根右左。这就启发我们,前序遍历的非递归代码基本不变,只需要将右孩子先入栈改为左孩子先入栈即可。这样得到的遍历顺序是:根右左。最后反转得到左右根

代码(递归)

 1 class Solution {
 2 public:
 3     void dfs(TreeNode* root,vector<int>&res){
 4         if(root == NULL) return;
 5 
 6         dfs(root->left,res);
 7         dfs(root->right,res);
 8         res.push_back(root->val);//对根的处理
 9     }
10     vector<int> postorderTraversal(TreeNode* root) {
11         vector<int>res;
12         dfs(root,res);
13         return res;
14     }
15 };

 代码(非递归)

 1 class Solution {
 2 public:
 3    
 4     vector<int> postorderTraversal(TreeNode* root) {
 5         stack<TreeNode*>s;
 6         vector<int>res;
 7         s.push(root);
 8 
 9         while(!s.empty()){
10             auto t = s.top();
11             s.pop();
12             if(t!=NULL) res.push_back(t->val);
13             else continue;
14             if(t->left!=NULL) s.push(t->left);
15             if(t->right!=NULL) s.push(t->right);
16         }
17         reverse(res.begin(),res.end());
18         return res;
19     }
20 };

 

posted @ 2021-02-22 21:34  Uitachi  阅读(50)  评论(0编辑  收藏  举报