美文网首页一起来刷算法题
binary-tree-postorder-traversal

binary-tree-postorder-traversal

作者: cherryleechen | 来源:发表于2019-05-08 20:07 被阅读0次

时间限制: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

相关文章

网友评论

    本文标题:binary-tree-postorder-traversal

    本文链接:https://www.haomeiwen.com/subject/pewvoqtx.html