1.题目
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
2.思路
- 根据前序的第一个数字1,判断出根节点为1,则【4,7,2,1】和【5,3,8,6】为它的左子序列和右子序列
- 再根据前序遍历查找【4,7,2】这个左子序列的中序遍历为【2,4,7】,可判断出这个左子序列根节点为2,【4,7】为它的左子序列
- 再由中序遍历【4,7】可知其根节点为4,则7为4的右子节点
- 右子序列【5,3,8,6】同样以此类推
3.代码实现
public class Solution {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
if (pre == null || pre.length == 0 || in == null || in.length == 0 || pre.length != in.length) {
return null;
}
return reConstructBinaryTree(pre, in, 0, pre.length - 1, 0, in.length - 1);
}
private TreeNode reConstructBinaryTree(int[] pre, int[] in, int pstart, int pend, int istart, int iend) {
TreeNode root = new TreeNode(pre[pstart]);
//当只有一个节点时
try {
if (pstart== pend&& istart==iend) {
if (pre[pstart]!=in[istart]) {
throw new Exception("前、中序列不合法");
}
return root;
}
} catch (Exception e) {
e.printStackTrace();
}
//当根节点存在子节点时,进行递归
int index = istart;
while (pre[pstart] != in[index]&&index<=iend) {
index++;
}
int leftlen = index - istart;
if (leftlen > 0) {
root.left=reConstructBinaryTree(pre, in, pstart + 1, pstart + leftlen, istart, index-1 );
}
if (leftlen< iend-istart) {
root.right=reConstructBinaryTree(pre, in, pstart + 1 + leftlen, pend, index + 1, iend);
}
return root;
/**
* 测试前序遍历
* @param root
*/
public static void printFront(TreeNode root) {
if(root==null){
return ;
}
System.out.print(root.val+"\t");
printFront(root.left);
printFront(root.right);
}
/**
* 测试中序遍历
* @param root
*/
public static void printMiddle(TreeNode root) {
if(root==null){
return ;
}
printMiddle(root.left);
System.out.print(root.val+"\t");
printMiddle(root.right);
}
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};
Solution solution = new Solution();
TreeNode treeNode = solution.reConstructBinaryTree(pre, in);
System.out.println("前序遍历:");
printFront(treeNode);
System.out.println();
System.out.println("中序遍历:");
printMiddle(treeNode);
}
}