LeetCode105 从前序和中序构建二叉树

本文详细解析了如何利用前序遍历与中序遍历构建二叉树的过程,通过递归算法实现,并介绍了使用HashMap存储中序遍历索引以提高查找效率的方法。

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

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

3

/
9 20
/
15 7
只能从前序中序或或 中序后序遍历构建,思路很简单就是扣细节,难得扣

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Map <Integer,Integer> map=new HashMap<>();//存储中序遍历中的索引
    public TreeNode robot(int[] preorder,int preL,int preR,int inL){
        if(preL>preR)
            return null;
        //先算好找到根的各个位置
        TreeNode root=new TreeNode(preorder[preL]);
        int index=map.get(root.val);//拿到对应的中序遍历的下标,方便算左右子树在数组的距离
        int lefttreesize=index-inL;
        root.left=robot(preorder,preL+1,lefttreesize+preL,inL);
        root.right=robot(preorder,preL + lefttreesize + 1, preR, inL + lefttreesize + 1);
        return root;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        //仿照大神先来个hashmap放中序遍历的索引
        for(int i=0;i<inorder.length;i++)
            map.put(inorder[i],i);
        return robot(preorder,0,preorder.length-1,0);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值