94. 二叉树的中序遍历

本文探讨了三种不同的算法技巧——递归、使用栈和镜像操作,来实现二叉树的中序遍历。通过实例代码展示了如何利用递归的inOrder函数、栈结构进行迭代,以及利用镜像反转法巧妙地遍历。这些方法有助于理解树形数据结构的不同遍历策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

001 递归调用

class Solution {
public:
 void inOrder(TreeNode* root, vector<int>&ans){
        if (root) {
            inOrder(root->left,ans);
            ans.push_back(root->val);
            inOrder(root->right,ans);
        }
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>ans;
        inOrder(root,ans);
        return ans;
    }
};

002 栈

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
         vector<int>ans;
       
        stack<TreeNode *> s;
        //这里判断的条件是 root 和 s 不为空
        while (root || !s.empty()) {
            
            while (root) {
                s.push(root);
                root = root->left;
            }
            //到达最左边 把结点弹出来 进行遍历
            root = s.top();
            s.pop();
            //将值放入集合中
            ans.push_back(root->val);
            //转向右子树
            root = root->right;
        }
       
        return ans;
    }
};

003 Mirros

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>ans;
        auto cur = root;
        while (cur) {
            if (cur->left) {
                auto pre = cur->left;
                while (pre->right && pre->right !=cur) {
                    pre = pre->right;
                }
                
                if (!pre->right) {
                    pre->right = cur;
                    cur = cur->left;
                }else{
                    ans.push_back(cur->val);
                    pre->right = nullptr;
                    cur = cur->right;
                }
            }else{
                ans.push_back(cur->val);
                cur = cur->right;
            }
        }
        return  ans;
    }
};

题目

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值