zoukankan      html  css  js  c++  java
  • Leetcode No.145 **

    给定一个二叉树,返回它的 后序 遍历。

    示例:

    输入: [1,null,2,3]  
       1
        
         2
        /
       3 
    
    输出: [3,2,1]

    如图,输出结果为:DEBFCA

                                

    解答:参考博客http://www.cnblogs.com/grandyang/p/4251757.html

    前序遍历与后序遍历之所以放在一块,说明两者具有很大的相似性,实际情况也确实如此。如果我们将前序遍历输出值颠倒顺序,那么就可以很相近于后序遍历。唯一的差别在于相同一层的节点

    也倒转了顺序,变成了从右到左而不是从左到右。所以需要将压栈的顺序略微调整一下:先压栈左侧,再压栈右侧,再通过颠倒结果顺序,最后得到反反得正,即正确的顺序。

    //145
    vector<int> postorderTraversal(TreeNode* root)
    {
        vector<int> res;
        if(root==NULL) return res;
        stack<TreeNode*> st;
        st.push(root);
        TreeNode* p;
        while(!st.empty())
        {
            p = st.top();
            st.pop();
            res.insert(res.begin(),p->val);
            if(p->left!=NULL) st.push(p->left);
            if(p->right!=NULL) st.push(p->right);
        }
        return res;
    }//145
    
    
  • 相关阅读:
    redis
    装饰器之functools与before_request
    版本
    git常用命令
    支付宝支付示例
    ContentType
    vue的基础使用
    es6简单介绍
    解析器、路由控制、分页与响应器
    元素水平居中的方法
  • 原文地址:https://www.cnblogs.com/2Bthebest1/p/10851841.html
Copyright © 2011-2022 走看看