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

猜你喜欢

转载自www.cnblogs.com/cherrychenlee/p/10834215.html