leetcode刷题记录 104 从前序与中序遍历序列构造二叉树

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

在这里插入图片描述
解这道题,我需要了解二叉树中前序遍历和中序遍历的特点。前序遍历的特点就是根结点是其遍历的第一个结点,而中序遍历则是按照左根右的顺序进行遍历,只要知道根结点的位置,我们就可以确定左子树和右子树的区间。所以我们可以从前序遍历中获取根结点,然后在中序遍历中定位到根结点的位置,我们就知道左右子树的长度。这样一来,我们就知道了左子树的前序遍历和中序遍历结果,以及右子树的前序遍历和中序遍历结果,我们就可以递归地对构造出左子树和右子树,再将这两颗子树接到根节点的左右位置。

我在这里遇到的难点就是怎么确定左右子树的区间。我们可以借助画图来理解如何确定。
在这里插入图片描述

代码如下:

class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int preLen = preorder.length;
        int inLen = inorder.length;
        Map<Integer, Integer> indexMap = new HashMap<>(preLen);
        for(int i = 0;i<inLen;i++){
            indexMap.put(inorder[i],i);//使用hashMap提升查找的效率
        }
        return buildTree(preorder,0,preLen-1,indexMap,0,inLen-1);
    }

    public TreeNode buildTree(int[]preorder,int preLeft,int preRight,Map<Integer,Integer>indexMap,int inLeft,int inRight){
        if(preLeft>preRight || inLeft>inRight){
            return null;
        }
        int pre_root = preorder[preLeft];
        int pIndex = indexMap.get(pre_root);//根据前序遍历的根结点定位其在中序遍历中的位置
        TreeNode root = new TreeNode(pre_root);
        root.left = buildTree(preorder,preLeft+1,pIndex-inLeft+preLeft,indexMap,inLeft,pIndex-1);
        root.right = buildTree(preorder,pIndex-inLeft+preLeft+1,preRight,indexMap,pIndex+1,inRight);

        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40453090/article/details/108372788
今日推荐