• 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

  • 相关阅读:
    bzoj4196: [Noi2015]软件包管理器
    bzoj3083: 遥远的国度
    bzoj4034: [HAOI2015]T2
    2.EXIT_KEY
    AD如何1比1打印
    编程时注意,
    同步事件、异步事件、轮询
    事件位
    挂起进程相关API
    PROCESS_EVENT_POLL事件
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10834215.html
Copyright © 2020-2023  润新知