zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    UVA 10905
    UVA 10859 树形DP
    LA 4794 状态DP+子集枚举
    LA 3695 部分枚举
    UVA 11825 状态压缩DP+子集思想
    UVA 10891 区间DP+博弈思想
    HDU 5239 上海大都会 D题(线段树+数论)
    HDU 5242 上海大都会 G题
    HDU 5241 上海大都会 F题
    P1359 租用游艇
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14433054.html
Copyright © 2011-2022 走看看