JZ7 重建二叉树 C++ 详细注释

该博客介绍了如何通过前序遍历和中序遍历的序列来重建二叉树。首先找到根节点,然后递归地构建左右子树。递归过程中,根据中序遍历找到根节点的位置,进而划分左右子树的序列,最后根据划分的序列继续构建子树,直至完成整个二叉树的构造。

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

https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
思路:先找出根结点,再递归构建左右子树

class Solution {
public:
    TreeNode *reConstructBinaryTree(vector<int> pre, vector<int> vin) {
        if (pre.empty() && vin.empty())     // 树为空
            return nullptr;
        TreeNode *root = new TreeNode(*pre.begin());     // 前序遍历的第一个结点为根结点
        // 在中序遍历中找到根结点的位置
        auto mid = find(vin.begin(),vin.end(),root->val);
        vector<int> leftin{vin.begin(),mid};       // 左子树的中序遍历序列
        vector<int> rightin{mid+1,vin.end()};      // 右子树的中序遍历序列
        int nleft = leftin.size();            // 左子树中的结点个数
        int nright = rightin.size();          // 右子树中的结点个数
        vector<int> leftpre{pre.begin()+1,pre.begin()+nleft+1};   // 左子树的前序遍历序列
        vector<int> rightpre{pre.end()-nright,pre.end()};         // 右子树的前序遍历序列
        if (nleft)      // 左子树不为空
            root->left = reConstructBinaryTree(leftpre,leftin);     // 递归构建左子树
        if (nright)     // 右子树不为空
            root->right = reConstructBinaryTree(rightpre,rightin);  // 递归构建右子树
        return root;    // 返回树根
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值