CodeTop049 从前序与中序遍历序列构造二叉树

从前序与中序遍历序列构造二叉树

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

这题就是多做几遍,想明白了就好了,记住一点,使用的indexMap是用来定位中序遍历根节点的index的,而且在下面定位的是前序根节点的index和中序根节点的index

详细说明看注释

class Solution {
    public Map<Integer,Integer> indexMap;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        indexMap = new HashMap<>();
        int n = inorder.length;
        for(int i=0;i<n;i++){
            indexMap.put(inorder[i],i);
        }
        return func(preorder,inorder,0,n-1,0,n-1) ;
    }

    public TreeNode func(int[] preorder, int[] inorder,int preorder_left,int preorder_right,int inorder_left,int inorder_right){
        if(preorder_left>preorder_right){
            return null;
        }

         // 前序遍历中的第一个节点就是根节点
         int preorder_root = preorder_left;
         // 在中序遍历中定位根节点的位置
         int inorder_root = indexMap.get(preorder[preorder_root]);
         // 先把根节点建立出来
         TreeNode root = new TreeNode(preorder[preorder_root]);
         // 得到左子树中的节点数目
         int size_leftTree = inorder_root-inorder_left;
         // 递归地构造左子树,并连接到根节点
        //先序遍历中「从 左边界+1 开始的 size_left_subtree」个元素就对应了中序遍历中「从 左边界 开始到 根节点定位-1」的元素
        //这边在特殊说明一下root.left即左节点  所以对应的是前序遍历中[preorder_left+1,preorder_left+size_leftTree](因为preorder_left就是根节点)
        //在中序遍历中对应的是[inorder_left,inorder_root-1](因为inorder_root就是根节点)
        root.left=func(preorder,inorder,preorder_left+1,preorder_left+size_leftTree,inorder_left,inorder_root-1);
         // 递归地构造右子树,并连接到根节点
        // 先序遍历中「从 左边界+1+左子树节点数目 开始到 右边界」的元素就对应了中序遍历中「从 根节点定位+1 到 右边界」的元素
        //这边在特殊说明一下root.right即右节点  所以对应的是前序遍历中[preorder_left+size_leftTree+1,preorder_right](因为preorder_left就是根节点)
        //在中序遍历中对应的是[inorder_root+1,inorder_right](因为inorder_root就是根节点)
        root.right=func(preorder,inorder,preorder_left+size_leftTree+1,preorder_right,inorder_root+1,inorder_right);
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值