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;
    }
}
相关推荐
lisw052 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
阿卡好可爱2 小时前
Lua 热更新不生效:改完文件线上仍是旧逻辑,package.loaded 与 upvalue 重绑定详解
数据结构·分布式·后端·架构·lua
一起学安全技术3 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs4 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信150413057594 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI15 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi16 小时前
力扣54.螺旋矩阵
算法·leetcode·矩阵
choumou_M18 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen19 小时前
罗克韦尔ACD工程归档离线变量树解析
算法·c#