LeetCode——105. Construct Binary Tree from Preorder and Inorder Traversal(C++)

这篇博客介绍了如何利用C++解决LeetCode上的105题,即根据给定的先序遍历和中序遍历数组构建二叉树。通过递归方法,首先找到先序遍历中的根节点,然后分别构建左子树和右子树,最终形成完整的二叉树结构。示例代码展示了具体的实现过程。
摘要由CSDN通过智能技术生成

LeetCode——105. Construct Binary Tree from Preorder and Inorder Traversal(C++)
Description:
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:
在这里插入图片描述
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
Constraints:

1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder and inorder consist of unique values.
Each value of inorder also appears in preorder.
preorder is guaranteed to be the preorder traversal of the tree.
inorder is guaranteed to be the inorder traversal of the tree.

题目解析:
给出中序遍历和先序遍历的数组,返回该二叉树;

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    TreeNode* BuildTree(vector<int>& in,vector<int>& pre,int inleft,int inright,int preleft,int preright)
    {
        if(inleft>inright)return NULL;
        TreeNode* cur=new TreeNode;
        cur->val=pre[preleft];
        int ind=inleft;
        while(in[ind]!=pre[preleft])ind++;
        cur->left=BuildTree(in,pre,inleft,ind-1,preleft+1,ind-inleft+preleft);
        cur->right=BuildTree(in,pre,ind+1,inright,ind-inleft+preleft+1,preright);
        return cur;
        
    }
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int sz=preorder.size();
        return BuildTree(inorder,preorder,0,sz-1,0,sz-1);
    }
};

Submission:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值