从前序与中序遍历序列构造二叉树

简介: 从前序与中序遍历序列构造二叉树

class TreeNode {

int val;
TreeNode left;
TreeNode right;

TreeNode(int x) {
    val = x;
}

}

public class Solution {

public TreeNode buildTree(int[] preorder, int[] inorder) {
    int preLen = preorder.length;
    int inLen = inorder.length;
    if (preLen != inLen) {
        throw new RuntimeException("Incorrect input data.");
    }
    return buildTree(preorder, 0, preLen - 1, inorder, 0, inLen - 1);
}

private TreeNode buildTree(int[] preorder, int preLeft, int preRight,
                           int[] inorder, int inLeft, int inRight) {
    // 因为是递归调用的方法,按照国际惯例,先写递归终止条件
    if (preLeft > preRight || inLeft > inRight) {
        return null;
    }
    // 先序遍历的起点元素很重要
    int pivot = preorder[preLeft];
    TreeNode root = new TreeNode(pivot);
    int pivotIndex = inLeft;
    // 严格上说还要做数组下标是否越界的判断 pivotIndex < inRight
    while (inorder[pivotIndex] != pivot) {
        pivotIndex++;
    }
    root.left = buildTree(preorder, preLeft + 1, pivotIndex - inLeft + preLeft,
            inorder, inLeft, pivotIndex - 1);
    root.right = buildTree(preorder, pivotIndex - inLeft + preLeft + 1, preRight,
            inorder, pivotIndex + 1, inRight);
    return root;
}

}

相关文章
|
监控 调度
队列的深度解析:链式队列的实现
队列的深度解析:链式队列的实现
|
IDE Java 编译器
关于win10下codeblock的中文乱码问题解决
乱码问题通常是由于不同平台编码不一致导致的。本文介绍了如何在 Code::Blocks 中解决这一问题,具体步骤包括选择编译器、配置编译选项,并添加 `-finput-charset=UTF-8` 和 `-fexec-charset=GBK` 参数。此外,还补充了一些常见的字符集知识。
|
机器学习/深度学习 算法 自动驾驶
深度学习之分布式智能体学习
基于深度学习的分布式智能体学习是一种针对多智能体系统的机器学习方法,旨在通过多个智能体协作、分布式决策和学习来解决复杂任务。这种方法特别适用于具有大规模数据、分散计算资源、或需要智能体彼此交互的应用场景。
903 4
|
存储 算法 C++
弗洛伊德(Floyd)算法(C/C++)
弗洛伊德(Floyd)算法(C/C++)
|
存储 编译器 C++
【C++篇】引领C++模板初体验:泛型编程的力量与妙用
【C++篇】引领C++模板初体验:泛型编程的力量与妙用
255 9
|
API
FreeRTOS入门教程(队列详细使用示例)
FreeRTOS入门教程(队列详细使用示例)
886 0
|
编译器
模板初阶(1):函数模板,类模板
模板初阶(1):函数模板,类模板
|
编解码 网络性能优化 芯片
如何用51单片机实现pwm调光+呼吸灯(超详细+源码)
如何用51单片机实现pwm调光+呼吸灯(超详细+源码)
2612 0
如何用51单片机实现pwm调光+呼吸灯(超详细+源码)
栈在求值表达式中的应用
栈在求值表达式中的应用
316 0

热门文章

最新文章