zoukankan      html  css  js  c++  java
  • binary-tree-postorder-traversal

    原文地址:https://www.jianshu.com/p/68e6562c666d

    时间限制:1秒 空间限制:32768K

    题目描述

    Given a binary tree, return the postorder traversal of its nodes' values.
    For example:
    Given binary tree{1,#,2,3},
    1

    2
    /
    3
    return[3,2,1].
    Note: Recursive solution is trivial, could you do it iteratively?

    我的代码

    /**
     * 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) {
            vector<int> res;
            if(root==nullptr)
                return res;
            stack<TreeNode*> st;
            st.push(root);
            TreeNode* pre=nullptr;
            while(!st.empty()){
                TreeNode* cur=st.top();
                if(((cur->left==nullptr)&&(cur->right==nullptr))
                   ||(pre!=nullptr&&(pre==cur->left||pre==cur->right))){
                    res.push_back(cur->val);
                    st.pop();
                    pre=cur;
                }
                else{
                    if(cur->right){
                        st.push(cur->right);
                    }
                    if(cur->left){
                        st.push(cur->left);
                    }
                }
            }
           return res;     
        }
    };
    

    运行时间:3ms
    占用内存:476k

    /**
     * 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) {
            vector<int> res;
            if(root==nullptr)
                return res;
            stack<TreeNode*> st;
            st.push(root);
            while(!st.empty()){
                TreeNode* cur=st.top();st.pop();
                res.push_back(cur->val);
                //根左右进,根右左出
                if(cur->left){
                    st.push(cur->left);
                }            
                if(cur->right){
                    st.push(cur->right);
                    }
            }
            //倒序
            reverse(res.begin(),res.end());
            return res;  
        }
    };
    

    运行时间:6ms
    占用内存:620k

  • 相关阅读:
    C#学习笔记
    Visual Studio 快捷键
    java 8 中lambda表达式学习
    Spfa算法
    dijkstra算法
    topSort
    并查集--学习详解
    trie树--详解
    POJ1988 并查集的使用
    Mybatis的一级缓存和二级缓存
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10834215.html
Copyright © 2011-2022 走看看