二叉树的前序遍历、中序遍历、后序遍历的非递归版本

二叉树的前序非递归遍历

思路:对每个结点按照 根->右->左 的顺序入栈,出栈的顺序就是前序遍历的结果。

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if(!root)
            return vector<int>();
        
        vector<int> res;
        stack<TreeNode*> sta;
        sta.push(root);
        while(!sta.empty())
        {
            TreeNode* head = sta.top();
            sta.pop();
            res.push_back(head->val);
            
            if(head->right)
                sta.push(head->right);
            if(head->left)
                sta.push(head->left);
        }
        
        return res;
    }
};

二叉树的中序遍历非递归

思路:
(1)树先一直向左走到叶节点并将沿途的结点入栈 ;
(2)然后向右走一步,重复第一步操作。
注意要将沿途的节点进行入栈

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> sta;
        
        TreeNode* head = root;
        while(head || !sta.empty())
        {
            while(head)
            {
                sta.push(head);
                head = head->left;
            }
            
            head = sta.top();
            res.push_back(head->val);
            sta.pop();
            
            head = head->right;
        }
        
        return res;
    }
};

二叉树的非递归后序遍历

利用栈实现,先按照 中->左->右的顺序遍历树并放入栈中(方法类似前序遍历中->左->右),然后将栈的数据转移到另一个栈中,遍历顺序就变成 左->右->中(后序顺序)

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if(!root)
            return vector<int>();
        
        vector<int> res;
        stack<TreeNode*> sta1,sta2;
        sta1.push(root);
        while(!sta1.empty())
        {
            TreeNode* cur = sta1.top();
            sta1.pop();
            sta2.push(cur);//注意这里的写法这样st2存储的顺序变成了根-右-左
            if(cur->left)
                sta1.push(cur->left);
            if(cur->right)
                sta1.push(cur->right);
        }
        
        while(!sta2.empty())
        {
            TreeNode* cur = sta2.top();
            sta2.pop();
            res.push_back(cur->val);
        }
        
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值