题⽬描述
输⼊某⼆叉树的前序遍历和中序遍历的结果,请重建出该⼆叉树。假设输⼊的前序遍历和中序遍历的结果中都不含重复的数字。例如输⼊前序遍历序列{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 |