Construct Binary Tree from Preorder and Inorder Traversal Java

本文详细介绍了如何使用哈希表和递归算法构建二叉树,从预序遍历和中序遍历出发,通过解析根节点和左右子树的位置关系,实现树的构建。

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

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Key to Solve: Recursion + HashMap(Key: Inorder's Node, Value: position)
    Preorder: we can see the top Root is 1st element of Preorder, and so on
    Inorder: the elements before the root are belong to left subtree
             after the root are belong to right subtree
    The split left and right subtree base on  value of Preorder
    and position of inorder

public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
  if(preorder.length==0 || inorder.length==0) return null;
        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int i=0;i<inorder.length;i++){

            map.put(inorder[i],i);
        }
        return helperRecur(preorder,inorder,0,preorder.length-1,0,inorder.length-1,map);
    }
    private TreeNode helperRecur(int[] preorder, int[] inorder, int preL, int preR,
                               int inL, int inR, HashMap<Integer,Integer> map){
        if(preL>preR || inL>inR){
            return  null;
        }
        TreeNode root=new TreeNode(preorder[preL]);
        int rootIndex=map.get(root.val);
        int distance=rootIndex-inL;
        root.left=helperRecur(preorder,inorder,preL+1,preL+distance,inL,rootIndex-1,map);
        root.right=helperRecur(preorder,inorder,preL+distance+1,preR,rootIndex+1,inR,map);

        return root;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值