二叉树的前中后序遍历(非递归)

class TreeNode
{
public:
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode():val(NULL),left(nullptr),right(nullptr){}
    TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) 
    {
        if(root == nullptr) return res;
        TreeNode *cur = root;
        sta.push(root);
        while(!sta.empty())
        {
            cur = sta.top();
            sta.pop();
            res.push_back(cur->val);
            //先压入右 左 ,出栈才能为左 右
            if(cur->right) sta.push(cur->right);
            if(cur->left) sta.push(cur->left);
        }
        return res;
    }
    vector<int> inorderTraversal(TreeNode* root)
    {
        if(root == nullptr) return res;
        TreeNode *cur = root;
        while(cur != nullptr || !sta.empty())
        {
            if(cur != nullptr)
            {
                sta.push(cur);
                cur = cur->left;
            }
            else{
                cur = sta.top();
                sta.pop();
                res.push_back(cur->val);
                cur = cur->right;
            }
        }
        return res;
    }
    vector<int> postorderTraversal(TreeNode* root)
    {
        if(root == nullptr) return res;
        TreeNode *cur = root;
        sta.push(root);
        while(!sta.empty())
        {
            cur = sta.top();
            sta.pop();
            res.push_back(cur->val);
            if(cur->left) sta.push(cur->left);
            if(cur->right) sta.push(cur->right);
        }
        reverse(res.begin(),res.end());
        return res;
    }

private:
    stack<TreeNode*> sta;
    vector<int> res;
};
posted @   xiazichengxi  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩