题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路分析:
因为是树的结构,一般都是用递归来实现。
用数学归纳法的思想就是,假设最后一步,就是root的左右子树都已经重建好了,那么我只要考虑将root的左右子树安上去即可。
1.先序遍历第一个位置肯定是根节点node,
2.中序遍历的根节点位置在中间rootIndex,在rootIndex左边的肯定是node的左子树的中序数组,rootIndex右边的肯定是node的右子树的中序数组
3.另一方面,先序遍历的第二个位置到rootIndex,也是node左子树的先序遍历数组,剩下rootIndex右边的就是node的右子树的先序遍历数组(重点!!!这个比较难想到)
4.把四个数组找出来,分左右递归调用即可
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
int[] pre={1,2,4,7,3,5,6,8};
int[] in={4,7,2,1,5,3,8,6};
TreeNode root = reConstructBinaryTree(pre, in);
root.preOrder();
}
/* 返回二叉树的根结点 */
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
// 数组长度为0时,要处理
if (pre.length == 0) {
return null;
}
// 1.使用递归要确定返回点,数组长度为1时,即为根结点,返回子树的根结点
if (pre.length == 1) {
return new TreeNode(pre[0]);
}
// 创建根结点
int rootValue = pre[0];
TreeNode root = new TreeNode(rootValue);
// 2.找到root在中序遍历时的下标rootIndex
int rootIndex = 0;
for (int i = 0; i < in.length; i++) {
if (in[i] == rootValue) {
rootIndex = i;
break;
}
}
// 3.递归。
// 中序遍历序列中,rootIndex左边为左子树的中序遍历序列,rootIndex右边为右子树的中序遍历序列
// 前序遍历序列中,1->rootIndex为左子树的前序遍历序列,rootIndex->pre.length-1为右子树的前序遍历序列
// 数学归纳法,假设最后一步,root左右子树已建立好,只要将左右子树的根节点安上去即可。
// 3.1 找到左子树根结点。Arrays.copyOfRange(int[] arr,int start,int end),有头无尾
int[] lChildPreOrderArr = Arrays.copyOfRange(pre, 1, rootIndex + 1);// 左子树的前序遍历序列
int[] lChildInOrderArr = Arrays.copyOfRange(in, 0, rootIndex);// 左子树的中序遍历序列
TreeNode leftNode = reConstructBinaryTree(lChildPreOrderArr, lChildInOrderArr);
// 3.2 找到右子树根结点。Arrays.copyOfRange(int[] arr,int start,int end),有头无尾
int[] rChildPreOrderArr = Arrays.copyOfRange(pre, rootIndex + 1, pre.length);
int[] rChildInOrderArr = Arrays.copyOfRange(in, rootIndex + 1, in.length);
TreeNode rightNode = reConstructBinaryTree(rChildPreOrderArr, rChildInOrderArr);
// 3.3 安上左右结点
root.left = leftNode;
root.right = rightNode;
return root;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
public void preOrder() {
System.out.print(this.val+" ");
if(this.left!=null) {
this.left.preOrder();
}
if(this.right!=null) {
this.right.preOrder();
}
}
}