力扣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;
    }
}
相关推荐
漫随流水10 小时前
leetcode算法(151.反转字符串中的单词)
数据结构·算法·leetcode
ada7_11 小时前
LeetCode(python)78.子集
开发语言·数据结构·python·算法·leetcode·职场和发展
DeepVis Research11 小时前
【AGI/Simulation】2026年度通用人工智能图灵测试与高频博弈仿真基准索引 (Benchmark Index)
大数据·人工智能·算法·数据集·量化交易
努力学算法的蒟蒻11 小时前
day52(1.3)——leetcode面试经典150
算法·leetcode·面试
leoufung11 小时前
LeetCode 97. 交错字符串 - 二维DP经典题解(C语言实现)
c语言·算法·leetcode
leiming614 小时前
c++ map容器
开发语言·c++·算法
杨校14 小时前
杨校老师课堂备赛C++信奥之模拟算法习题专项训练
开发语言·c++·算法
世洋Blog14 小时前
AStar算法基础学习总结
算法·面试·c#·astar·寻路
haing201914 小时前
七轴协作机器人运动学正解计算方法
算法·机器学习·机器人