题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
示例:
输入:
前序遍历:1, 2, 3, 4, 5, 6, 7
中序遍历:3, 2, 4, 1, 6, 5, 7
输出:1, 2, 5, 3, 4, 6, 7
分析:
前序遍历的第一个节点为二叉树的根节点,找到根节点在中序遍历数组中的位置,则前半部分就为根节点的左子树节点,后半部分就为根节点的右子树节点。
使用递归结构,重建二叉树即可。
实现:
重建二叉树的方法为:
/**
* 根据先序遍历和中序遍历,重建二叉树
* @param pre 先序遍历数组
* @param in 中序遍历数组
* @return 返回根节点
*/
public static TreeNode reConstructBinaryTree(int[] pre,int[] in){
if(pre.length == 0){
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<in.length;i++){
if(pre[0] == in[i]){
rootIndex = i;
}
}
//截取左子树的先序和中序遍历数组
int[] preArr1 = Arrays.copyOfRange(pre,1,rootIndex+1);
int[] inArr1 = Arrays.copyOfRange(in,0,rootIndex);
//截取右子树的先序和中序遍历结果
int[] preArr2 = Arrays.copyOfRange(pre,rootIndex+1,pre.length);
int[] inArr2 = Arrays.copyOfRange(in,rootIndex+1,in.length);
root.left = reConstructBinaryTree(preArr1,inArr1);
root.right = reConstructBinaryTree(preArr2,inArr2);
return root;
}
树节点结构如下所示,包含打印链表的方法:
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
//打印链表
public void show(){
Queue<TreeNode> queue = new ArrayDeque<>();
TreeNode temp = this;
while (temp != null){
if(temp.left != null){
queue.add(temp.left);
}
if(temp.right != null){
queue.add(temp.right);
}
System.out.print(temp.val + " ");
temp = queue.poll();
}
}
}