105. 从前序与中序遍历序列构造二叉树/C++

本文介绍了一种使用前序遍历和中序遍历构建二叉树的方法。通过找到根节点和左右子树,然后递归地构建整棵树。具体实现包括定义二叉树节点结构,以及构建树的函数。

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

在这里插入图片描述
就是在两种序列中,找到根节点与左右子树,之后就是递归了。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    }
    TreeNode* build(vector<int>& preorder, int startPre, int endPre, vector<int>& inorder, int startIn, int endIn){
        if(startPre>endPre || startIn>endIn) return nullptr;
        
        int rootVal = preorder[startPre];
        TreeNode* root = new TreeNode(rootVal);
        if(startPre==endPre) return root;
        
        int rootIn = startIn;
        while(rootIn<=endIn && inorder[rootIn]!=rootVal)
            ++rootIn;
        
        int lenLeft = rootIn - startIn;
        root->left = build(preorder,startPre+1,startPre+lenLeft,inorder,startIn,rootIn-1);
        root->right = build(preorder,startPre+lenLeft+1,endPre,inorder,rootIn+1,endIn);
        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值