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

  • 相关阅读:
    memcpy源代码
    XML总结
    javabean总结
    VC++注射过程
    八排序算法
    fscanf功能具体解释
    外行观察者模式
    Android 实现用户列表信息的功能,然后选择删除幻灯片删除功能
    WINHTTP的API接口说明
    poj 1698 Alice&#39;s Chance 拆点最大流
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10834215.html
Copyright © 2011-2022 走看看