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;
    }
}
相关推荐
ltl21 分钟前
HNSW:图索引如何击败树索引
算法
曹牧2 小时前
C#:数字的定义和表示方式
算法·c#
Nil2082 小时前
leetcode 138随机链表的复制
算法·leetcode·链表
疯狂打码的少年4 小时前
【数据结构】图的遍历:深度优先搜索(DFS)
数据结构·笔记·算法·深度优先
-凌凌漆-5 小时前
【freertos】Task创建(v2)
java·开发语言·算法
Nil2085 小时前
leetcode 24两两交换链表中的节点
算法·leetcode·链表
.格子衫.5 小时前
033动态规划之状态压缩DP——算法备赛
算法·动态规划
ysa0510306 小时前
c++常用自带函数用法与注意
c++·笔记·算法
带多刺的玫瑰7 小时前
Leecode#4刷题之寻找两个正序数组的中位数
java·前端·算法