力扣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;
    }
}
相关推荐
大江东去浪淘尽千古风流人物32 分钟前
【VLN】VLN(Vision-and-Language Navigation视觉语言导航)算法本质,范式难点及解决方向(1)
人工智能·python·算法
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a003-列表-排序
开发语言·数据结构·python
wuhen_n1 小时前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
努力学算法的蒟蒻1 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495641 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
AC赳赳老秦1 小时前
2026国产算力新周期:DeepSeek实战适配英伟达H200,引领大模型训练效率跃升
大数据·前端·人工智能·算法·tidb·memcache·deepseek
独好紫罗兰2 小时前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
2401_841495642 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
budingxiaomoli2 小时前
优选算法-字符串
算法
我是咸鱼不闲呀2 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划