题目:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},请重建二叉树并返回。
思路:
(1)首先根据根节点a将中序遍历划分为两部分,左边为左子树,右边为右子树
(2) 在左子树和右子树分布根据上述规则递归,得出左、右边子树。
package codingquestions;
import java.util.Arrays;
class BinaryTreeNode{
int val;
BinaryTreeNode left;
BinaryTreeNode right;
BinaryTreeNode(int x) {val=x;}
}
public class ReconstructBinaryTree {
public static BinaryTreeNode reconstruct(int[] pre, int[] in) {
if(pre==null || in==null) {return null;}
if(pre.length==0 || in.length==0) {return null;}
if(pre.length!=in.length) {return null;}
//根据前序,确定根的值
BinaryTreeNode root=new BinaryTreeNode(pre[0]);
for(int i=0;i<in.length;i++) {
if(root.val==in[i]) {
root.left=reconstruct(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in,0,i));
root.right=reconstruct(Arrays.copyOfRange(pre, i+1, pre.length), Arrays.copyOfRange(in,i+1,in.length));
}
}
return root;
}
//后序遍历打印二叉树
public static void postprint(BinaryTreeNode head) {
if (head==null) {return;}
postprint(head.left);
postprint(head.right);
System.out.print(head.val+" ");
}
//测试用例
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};
BinaryTreeNode root =reconstruct(pre, in);
postprint(root);
}
}
此外,还可以根据后序 {7,4,2,5,8,6,3,1} 和中序{4,7,2,1,5,3,8,6}结果来重建二叉树,并用前序打印出来。
package codingquestions;
import java.util.Arrays;
public class ReconstructBinaryTree1 {
public static BinaryTreeNode reconstruct(int[] post, int[] in) {
if(post==null || in==null) {return null;}
if(post.length==0 || in.length==0) {return null;}
if(post.length!=in.length) {return null;}
//根据前序,确定根的值
BinaryTreeNode root=new BinaryTreeNode(post[post.length-1]);
for(int i=0;i<in.length;i++) {
if(root.val==in[i]) {
root.left=reconstruct(Arrays.copyOfRange(post, 0, i), Arrays.copyOfRange(in,0,i));
root.right=reconstruct(Arrays.copyOfRange(post, i, post.length-1), Arrays.copyOfRange(in,i+1,in.length));
}
}
return root;
}
//前序遍历打印二叉树
public static void preprint(BinaryTreeNode head) {
if (head==null) {return;}
System.out.print(head.val+" ");
preprint(head.left);
preprint(head.right);
}
//测试用例
public static void main(String[] args) {
int[] pre = {7,4,2,5,8,6,3,1};
int[] in ={4,7,2,1,5,3,8,6};
BinaryTreeNode root =reconstruct(pre, in);
preprint(root);
}
}