栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Leecode 145. 二叉树的后序遍历 递归/迭代

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leecode 145. 二叉树的后序遍历 递归/迭代

原题链接:Leecode 145. 二叉树的后序遍历


递归:

class Solution {
public:
    void postorder(TreeNode* root,vector& res)
    {
        if(!root) return ;
        postorder(root->left,res);
        postorder(root->right,res);
        res.push_back(root->val);
    }
    vector postorderTraversal(TreeNode* root) {
        vector res;
        postorder(root,res);
        return res;
    }
};

迭代(自己写的):

class Solution {
public:
    vector postorderTraversal(TreeNode* root) {
        vector res;
        if(!root) return {};
        stack st;
        st.push(root);
        map m;
        while(!st.empty())
        {
            while(st.top() && !(m[root->left]==1 && m[root->right]==1))
            {
                root=st.top();
                st.push(root->right);
                st.push(root->left);
            }
            while(st.top()==nullptr)
            {
                m[st.top()]=1;
                st.pop();
            }
            root=st.top();
            if(m[root->left]==1 && m[root->right]==1)
            {
                st.pop();
                res.push_back(root->val);
                m[root]=1;
            }
        }
        return res;
    }
};

迭代(官解)

class Solution {
public:
    vector postorderTraversal(TreeNode* root) {
        vector res;
        if(!root) return {};
        stack st;
        TreeNode* pre;
        while(!st.empty() || root!=nullptr)
        {
            while(root)
            {
                st.push(root);
                root=root->left;
            }
            root=st.top(); st.pop();
            if(root->right==nullptr || root->right==pre)
            {
                res.push_back(root->val);
                pre=root;
                root=nullptr;
            }
            else
            {
                st.push(root);
                root=root->right;
            }
        }
        return res;
    }
};

迭代(另一种写法)

class Solution {
public:
    vector postorderTraversal(TreeNode* root) {
        vector res;
        if(!root) return {};
        stack st;
        st.push(root);
        map m;
        while(!st.empty())
        {
            root=st.top();
            if((!root->left && !root->right) || m[root])
            {
                st.pop();
                res.push_back(root->val);
                continue;
            }
            if(root->right) st.push(root->right);
            if(root->left) st.push(root->left);
            m[root]=1;
        }
        return res;
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857919.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号