力扣105---从前序与中序序列中构造二叉树

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

示例 1:

输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

输出: [3,9,20,null,null,15,7]

示例 2:

输入: preorder = [-1], inorder = [-1]

输出: [-1]

代码:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length==0){//判断数组长度,如果为零,说明没有了
            return null;
        }
        int rootValue=preorder[0];//从先序遍历中获得父亲结点的值
        TreeNode node=new TreeNode(rootValue);//创建结点
        for(int i=0;i<inorder.length;i++){
            if(inorder[i]==rootValue){//从中序遍历中找到父亲节点的值,划分为左子树和右子树
                int[] preLeft = Arrays.copyOfRange(preorder, 1, i+1);//先序遍历中左子树的部分
                int[] preRight = Arrays.copyOfRange(preorder, i+1, preorder.length);//先序遍历中右子树的部分

                int[] inLeft = Arrays.copyOfRange(inorder, 0, i);//中序遍历中左子树的部分
                int[] inRight = Arrays.copyOfRange(inorder, i + 1, inorder.length);//中序遍历中左子树的部分

                node.left = buildTree(preLeft, inLeft);//递归调用左子树
                node.right=buildTree(preRight,inRight);//递归调用右子树
                break;//减少不必要的遍历
            }
        }
        return node;
    }
}
相关推荐
tju新生代魔迷6 分钟前
数据结构:双向链表
数据结构·链表
一只懒洋洋15 分钟前
K-meas 聚类、KNN算法、决策树、随机森林
算法·决策树·聚类
方案开发PCBA抄板芯片解密1 小时前
什么是算法:高效解决问题的逻辑框架
算法
songx_992 小时前
leetcode9(跳跃游戏)
数据结构·算法·游戏
学c语言的枫子2 小时前
数据结构——双向链表
c语言·数据结构·链表
小白狮ww2 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥2 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
Boop_wu3 小时前
[数据结构] 栈 · Stack
数据结构
kk”3 小时前
C语言快速排序
数据结构·算法·排序算法
纪元A梦3 小时前
贪心算法应用:基因编辑靶点选择问题详解
算法·贪心算法