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;
    }
}
相关推荐
wuweijianlove7 分钟前
算法性能的渐近与非渐近行为对比的技术4
算法
_dindong16 分钟前
cf1091div2 C.Grid Covering(数论)
c++·算法
AI成长日志16 分钟前
【Agentic RL】1.1 什么是Agentic RL:从传统RL到智能体学习
人工智能·学习·算法
黎阳之光1 小时前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生
skywalker_111 小时前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg1 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒1 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
计算机安禾2 小时前
【数据结构与算法】第36篇:排序大总结:稳定性、时间复杂度与适用场景
c语言·数据结构·c++·算法·链表·线性回归·visual studio
SatVision炼金士2 小时前
合成孔径雷达干涉测量(InSAR)沉降监测算法体系
算法