hot100-44从前序与中序遍历构造二叉树

一、题目

给出两个整数数组,前序遍历preorder和中序遍历inorder,请构造二叉树并返回根节点。

二、思路

1、前序遍历:根左右,第一个元素就是根节点,中序遍历,左根右,根节点左边左子树,右边右子树。

2、遍历中序遍历的数组,记录下值对应的index,便于寻找根节点的索引。

前序遍历数组的第一个值为根节点,找到根节点在中序遍历数组中的索引位置,分别通过左右子树在前序遍历和中序遍历的索引范围构建左子树和右子树。

递归的种植条件是,前序遍历的左边界>右边界。

三、代码

java 复制代码
class Solution {
    HashMap<Integer,Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for(int i = 0;i<inorder.length;i++){
            map.put(inorder[i],i);
        }
        return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }
    public TreeNode build(int[] preorder,int preStartIndex,int preEndIndex,int[] inorder,int inStartIndex,int inEndIndex){
        if(preStartIndex > preEndIndex || inStartIndex > inEndIndex) return null;
        int index = map.get(preorder[preStartIndex]);
        int leftSize = index - inStartIndex;
        TreeNode root = new TreeNode();
        root.val = inorder[index];
        root.left = build(preorder,preStartIndex+1,preStartIndex+leftSize,inorder,inStartIndex,index-1);
        root.right = build(preorder,preStartIndex+leftSize+1,preEndIndex,inorder,index+1,inEndIndex);
        return root;
    }
}
相关推荐
blxr_43 分钟前
力扣hot100爬楼梯https://leetcode.cn/problems/climbing-stairs/
算法·leetcode·职场和发展
pride.li1 小时前
ISP标定-NR标定(Noise Reduction,降噪校准)
算法·计算机视觉·isp
CQU_JIAKE1 小时前
9.29【A】
算法·深度优先
没落之王2 小时前
AI在文言文——论文脉复苏对AI的意义
大数据·人工智能·算法
u0111026752 小时前
工具页案例图如何编写 alt让图片说明与处理场景对应
java·前端·javascript·图像处理·人工智能·算法·ai作画
阿狗童鞋2 小时前
数据结构与算法实战指南
数据结构·算法
Navigator_Z2 小时前
LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
c语言·算法·leetcode
未来之窗软件服务2 小时前
递归时间复杂度演算T (n)=aT (n/b)+f (n)-东方仙盟
算法·仙盟创梦ide·东方仙盟
垆边人似月.3 小时前
华为机考题:明明的随机数
数据结构·算法·华为
Doubbbbbbble云3 小时前
多维空间索引结构R树与KD树性能对比研究4
算法