题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
* 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
* 例如:前序遍历序列{ 1, 2, 4, 7, 3, 5, 6, 8}和
* 中序遍历序列{4, 7, 2, 1, 5, 3, 8,6},
其中最重要的就是两句核心代码,理解起来还是有点难度的,但是多瞅几遍应也没有什么大的问题
/*
* 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
* 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
* 例如:前序遍历序列{ 1, 2, 4, 7, 3, 5, 6, 8}和
* 中序遍历序列{4, 7, 2, 1, 5, 3, 8,6},
* 重建出下图所示的二叉树并输出它的头结点。
*/
package 剑指offer;
import java.util.*;
public class Test06{
public static void main(String args[]){
test1();
}
public static void printTree(BinaryTreeNode root){
//中序遍历
if(root != null){
printTree(root.left);
System.out.print(root.value+" ");
printTree(root.right);
}
}
// 普通二叉树
// 1
// / \
// 2 3
// / / \
// 4 5 6
// \ /
// 7 8
public static void test1() {
int[] preorder = {1, 2, 4, 7, 3, 5, 6, 8};
int[] inorder = {4, 7, 2, 1, 5, 3, 8, 6};
BinaryTreeNode root = construct(preorder, inorder);
printTree(root);
}
public static class BinaryTreeNode{
// 定义二叉树结点
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
public static BinaryTreeNode construct(int preorder[], int inorder[]){
if(preorder == null || inorder == null || preorder.length != inorder.length){
return null;
}
return construct(preorder, 0, preorder.length - 1, inorder, 0, inorder.length -1);
}
public static BinaryTreeNode construct(int preorder[], int ps, int pe,
int inorder[], int is, int ie){
if(ps > pe || is > ie){
return null;
}
int value = preorder[ps];
int index = is;
while(index < ie && inorder[index] != value){
index++;
if(index > ie){
throw new RuntimeException("Error");
}
}
BinaryTreeNode node = new BinaryTreeNode();
node.value = value;
// 递归构建当前根结点的左子树,左子树的元素个数:index-is+1个
// 左子树对应的前序遍历的位置在[ps+1, ps+index-is]
// 左子树对应的中序遍历的位置在[is, index-1]
node.left = construct(preorder, ps + 1, ps + index - is, inorder, is, index - 1);
// 递归构建当前根结点的右子树,右子树的元素个数:ie-index个
// 右子树对应的前序遍历的位置在[ps+index-is+1, pe]
// 右子树对应的中序遍历的位置在[index+1, ie]
node.right = construct(preorder, ps + index - is + 1, pe, inorder, index + 1, ie);
return node;
}
}
其中test1()是重写构建二叉树的函数体
可以参考下下面这篇文章:
https://blog.csdn.net/qq_31726419/article/details/78364858
注意细节,背诵优质代码