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

时间:2021-09-03
本文章向大家介绍leetcode105 从前序与中序遍历序列中构造二叉树,主要包括leetcode105 从前序与中序遍历序列中构造二叉树使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
示例 1:

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:

Input: preorder = [-1], inorder = [-1]
Output: [-1]

1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder 和 inorder 均无重复元素
inorder 均出现在 preorder
preorder 保证为二叉树的前序遍历序列
inorder 保证为二叉树的中序遍历序列

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这个题目主要明白先序遍历中确定根,因为递归的每一层中的先序遍历的第一个值总是根
而中序遍历是为了确定左子树中节点的个数和右子树中节点的个数

 public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length==0)
            return null;
        HashMap<Integer,Integer> map=new HashMap<>();//建立hashmap的作用是方便查找根节点在中序遍历中的索引,这样根索引-中序左边界得到左子树中节点的个数,中序右边界-根索引得到右子树中节点的个数。
        for(int i=0;i<inorder.length;i++)
        {
            map.put(inorder[i],i);
        }
        return RecurBuid(map,0,preorder.length-1,preorder,0,inorder.length-1);
    }
    public TreeNode RecurBuid(HashMap<Integer,Integer> map,int preOderLeft,int preOderRight,int[] preorder,int inOderLeft,int inOrderRight)
    {
        if(preOderLeft>preOderRight)
           return null;
       int preOderRootIndex=preOderLeft;
       int inOrderRootIndex=map.get(preorder[preOderRootIndex]);

       TreeNode root=new TreeNode(preorder[preOderRootIndex]);

       int leftCount=inOrderRootIndex-inOderLeft;//确定左子树中节点的个数,为什么不是右子树??因为先序遍历中根节点后面首先根的左子树

       root.left=RecurBuid(map,preOderRootIndex+1,preOderLeft+leftCount,preorder,inOderLeft,inOrderRootIndex-1);
       root.right=RecurBuid(map,preOderLeft+leftCount+1,preOderRight,preorder,inOrderRootIndex+1,inOrderRight);

        return root;
    }

原文地址:https://www.cnblogs.com/AI-Creator/p/15222103.html