题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并输出它的后序遍历序列。
九度:http://ac.jobdu.com/problem.php?pid=1385
package com.offer.chapter_2;
import java.util.Scanner;
class TreeNode {
public int elem;
public TreeNode left;
public TreeNode right;
}
public class Interviews_6 {
public static boolean flag = true;
public static TreeNode constructorTree(int[] preOrder, int preStart, int preEnd, int[] inOrder, int inStart, int inEnd) {
TreeNode curRoot = new TreeNode();
curRoot.elem = preOrder[preStart];
curRoot.left = curRoot.right = null;
// 如果当前前序遍历中只有一个元素
if(preStart == preEnd) {
// 当前中序遍历也之后一个元素,并且元素相等
if(inStart == inEnd && preOrder[preStart] == inOrder[inStart]) {
return curRoot;
} else {
flag = false;
return null;
}
}
// 找到当前前序中第一个元素在中序遍历中索引位置
int inMid = -1;
for(int i =inStart; i<=inEnd; i++) {
if(preOrder[preStart] == inOrder[i]) {
inMid = i;
break;
}
}
// 当前前序遍历元素在中序遍历中不存在
if(inMid == -1) {
flag = false;
return null;
}
int leftLength = inMid - inStart;
int rightLength = inEnd - inMid;
// 递归构建左右子树
if(leftLength > 0) {
curRoot.left = constructorTree(preOrder, preStart+1, preStart + leftLength, inOrder, inStart, inMid - 1);
}
if(flag == false) {
return null;
}
if(rightLength > 0) {
curRoot.right = constructorTree(preOrder, preStart+leftLength + 1, preEnd, inOrder, inMid + 1 , inEnd);
}
if(flag == false) {
return null;
}
return curRoot;
}
public static TreeNode rebuildTree(int num, int[] preOrder, int[] inOrder) {
// 如果前序以及后序元素个数不相等或者num<0
if(preOrder.length != inOrder.length || preOrder.length != num || num < 0) {
flag = false;
return null;
}
// 构建二叉树
return constructorTree(preOrder, 0, preOrder.length -1, inOrder, 0, inOrder.length -1);
}
public static void PrintTree(TreeNode root) {
if(root != null) {
PrintTree(root.left);
PrintTree(root.right);
System.out.print(root.elem + " ");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
flag = true;
int num = scanner.nextInt();
int[] preOrder = new int[num];
int[] inOrder = new int[num];
for(int i=0; i<num; i++) {
preOrder[i] = scanner.nextInt();
}
for(int j=0; j<num; j++) {
inOrder[j] = scanner.nextInt();
}
TreeNode root = null;
root = rebuildTree(num, preOrder, inOrder);
if(flag == false) {
System.out.print("No");
} else {
PrintTree(root);
}
System.out.println();
}
}
}