题目:输入某二叉树的前序遍历和中序遍历的结果,重建该二叉树。假设输入的前序遍历和中序遍历的结果都不包含重复的数字。例如,前序遍历{1,2,4,7,3,5,6,8},中序遍历{4,7,2,1,5,3,8,6},则重建该二叉树,并输出头节点。
思路:根据根节点和根节点左右两边的值来确定左右子树,然后递归实现
/**
* @author: zjay
* @version: 1.0
* @date: 2021/8/12
*/
public class Test7_BinaryTreeConstruct {
public static void main(String[] args) {
int[] pre = {1,2,4,7,3,5,6,8};
//int[] pre = { }; //空树测试
//int[] pre = {1}; //一个节点测试
int[] infix = {4,7,2,1,5,3,8,6};
TreeNode root = constructBTree(pre,infix);
if(root != null) { //判断树是否为空
System.out.println(root.val);
} else {
System.out.println("树为空!!");
}
}
public static TreeNode constructBTree(int[] pre, int[] infix){
// 空二叉树判断
if(pre.length == 0 || pre == null || infix.length == 0||infix==null) {
return null;
}
//前序遍历和中序遍历的数据量不一样
if(pre.length != infix.length) {
return null;
}
// 一个节点的树
if(pre.length == 1) {
return new TreeNode(pre[0]);
}
//思路分析,根据根节点和根节点左右两边的值来确定左右子树
// 第一趟,确定根节点
TreeNode root = new TreeNode(pre[0]);
int rootIndex = 0;
for(int i = 0; i<infix.length;i++) {
if(infix[i] == root.val) {
rootIndex = i;
break;
}
}
//创建左子树
if(rootIndex > 0) {
int[] pre2 = new int[rootIndex];
int[] infix2 = new int[rootIndex];
for(int i=0; i < rootIndex; i++) { //根据左子树,遍历
pre2[i] = pre[i+1];
infix2[i] = infix[i];
}
root.left = constructBTree(pre2,infix2);
} else {
root.left = null;
}
// 创建右子树
if(infix.length-rootIndex-1 > 0) {
int[] pre2r = new int[infix.length-rootIndex-1];
int[] infix2r = new int[infix.length-rootIndex-1];
for(int i = 0; i < pre2r.length; i++) {
infix2r[i] = infix[rootIndex+1];
pre2r[i] = pre[rootIndex+1];
}
root.right = constructBTree(pre2r,infix2r);
} else {
root.right = null;
}
return root;
}
}
//树节点定义
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}