剑指offer-4、重建二叉树

[复制链接]
发表于 2025-6-26 09:37:38 | 显示全部楼层 |阅读模式
题⽬描述

输⼊某⼆叉树的前序遍历和中序遍历的结果,请重建出该⼆叉树。假设输⼊的前序遍历和中序遍历的结果中都不含重复的数字。例如输⼊前序遍历序列{1,2,4,7,3,5,6,8} 和中序遍历序列{4,7,2,1,5,3,8,6} ,则重建⼆叉树并返回。
思路及解答

递归办理


看上⾯的图⽚,⾸先数据包管了正确性,那么前序的第⼀个肯定是root 节点,也就是1 ,那么就必要在中序遍历中找到1 的位置,左边就是这个root 的左⼦树,右边就是root 的右⼦树。
举个例子:对根节点的左⼦树进⾏解析:

对右⼦树进⾏解析:

只必要不停递归即可,当边界左边⼤于右边的时间,则停⽌。
[code]```java/*** Definition for binary tree* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/public class Solution {        public TreeNode reConstructBinaryTree(int[] pre, int[] in) {                if (pre == null || pre.length == 0 || in == null || in.length == 0) {                        return null;                }                                TreeNode root = constructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length-1);                return root;                }                TreeNode constructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) {                // 不符合条件直接返回null                if (startPre > endPre || startIn > endIn) {                        return null;                }                // 构建根节点                TreeNode root = new TreeNode(pre[startPre]);                for (int index = startIn; index

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表