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;
    }
}
相关推荐
一只齐刘海的猫3 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏1113 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
liulilittle4 小时前
固定数组时间轮的槽过载优化:桶链表与批次执行
网络·数据结构·链表
IronMurphy4 小时前
【算法五十七】146. LRU 缓存
算法·缓存
Irissgwe4 小时前
数据结构-栈和队列
数据结构·c++·c·栈和队列
两片空白5 小时前
数据容器集合set/frozenset
数据结构
凌波粒5 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle5 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂5 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠5 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法