栈模拟先序后序中序遍历(非递归遍历)

先序遍历:

vector<int> preorderTraversal(TreeNode* u) {
        stack<TreeNode*>stk;
        vector<int>res;
        if(u==nullptr) return res;
        while(stk.size()||u){
            if(u){
                res.push_back(u->val);//遍历当前结点
                stk.push(u);//记录当前递归层
                u=u->left;//遍历左子树
            }else {
                u=stk.top();stk.pop();//返回上一层递归层
                u=u->right;//遍历右子树
            }
        }
        return res;
    }

优化版:

vector<int> preorderTraversal(TreeNode* u) {
        stack<TreeNode*>stk;
        vector<int>res;
        if(u==nullptr) return res;

        stk.push(u);
        while(stk.size()){
            auto t=stk.top();stk.pop();
            res.push_back(t->val);
            if(t->right)stk.push(t->right);//后遍历的先入栈,即右子树先入栈
            if(t->left)stk.push(t->left);//先遍历的后入栈,即左子树后入栈
        }
        return res;
    }

后序遍历:

后序遍历与先序遍历有互通之处,即后序遍历的倒序为:根右左。

所以我们可以把先序遍历的左右子树的遍历顺序倒一下便变成了后序遍历的倒序。

vector<int> postorderTraversal(TreeNode* u) {
        stack<TreeNode*>stk;
        vector<int>res;
        if(u==nullptr) return res;
        
        while(stk.size()||u){
            if(u){
                res.push_back(u->val);//遍历当前结点
                stk.push(u);//记录下该层的遍历
                u=u->right;//先遍历右子树
            }else {
                u=stk.top();stk.pop();
                u=u->left;//再遍历左子树
            }
        }
        reverse(res.begin(),res.end());
        return res;
    }

同样有优化版:

vector<int> postorderTraversal(TreeNode* u) {
        stack<TreeNode*>stk;
        vector<int>res;
        if(u==nullptr) return res;
        stk.push(u);
        while(stk.size()){
            TreeNode* t=stk.top();stk.pop();
            res.push_back(t->val);
            if(t->left)stk.push(t->left);
            if(t->right)stk.push(t->right);
        }
        reverse(res.begin(),res.end());
        return res;
    }

中序遍历:

vector<int> inorderTraversal(TreeNode* root) {
        vector<int>res;
        stack<TreeNode*>stk;
        while(stk.size()||root)
        {
            if(root)
            {
               	stk.push(root);//相当于记录下了当前层递归
           		root=root->left;//先遍历左子树
            }
            else
            {
                root=stk.top();//返回上一层递归
                stk.pop();
                res.push_back(root);//遍历当前结点
                root=root->right;//遍历右子树
            }
        }
        return res;
    }

中序遍历没有找到优化版,, 

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值