import java.util.Scanner;
public class LastBinaryTree {
/**
* 此题输入一组数据,便输出一个结果,都放在while循环里面,否则如果等while循环把所有输入读进去,
* 再输出结果的话,程序不知道什么时候才停止输入,因此一直等待下一个输入,而不会有输出
*
* /**
* 根据前序遍历和中序遍历重建二叉树子树
* @param preOrder 前序遍历数组
* @param start 子树起始位置
* @param inOrder 中序遍历数组
* @param end 中序遍历结束位置
* @param length 子树节点树
* @return 子树的根节点
*/
public static void main(String[] args) {
Scanner sin=new Scanner(System.in);
String s1=null;
String s2=null;
while(sin.hasNext()){
s1=sin.nextLine();
s2=sin.nextLine();
char[] preOrder = s1.toCharArray();
char[] inOrder = s2.toCharArray();
Node root = buildTree(preOrder, 0, inOrder, inOrder.length - 1, inOrder.length);
LastPrint(root);
System.out.println();
}
}
private static void LastPrint(Node root) {
if(root.left!=null)
LastPrint(root.left);
if(root.right!=null)
LastPrint(root.right);
System.out.print(root.value);
}
public static Node buildTree(char[] preOrder, int start, //返回根节点
char[] inOrder, int end, int length) {
//参数验证
if(preOrder==null||inOrder==null||preOrder.length==0||inOrder.length==0||length<=0)
return null;
//建立子树根节点
Node root=new Node();
root.value=preOrder[start];
//递归终止条件:子树只有一个节点
if(length==1)
return root;
//分拆子树的左子树和右子树
int i=0;
for( i=0;i<length;i++){
if(root.value==inOrder[end-i]) //查找中序序列中根节点的索引,i等于右子树的节点数
break;
}
//建立子树的左子树
root.left=buildTree(preOrder, start+1, inOrder, end-i-1, length-1-i);
//建立子树的右子树
root.right=buildTree(preOrder,start + length - i, inOrder, end, i); //下标要注意,很容易搞错,start + length - i写成end-i是不对的,为什么呢?还有点没搞懂
return root;
}
}
class Node {
Node left = null;
Node right = null;
char value;
}
转载于:https://www.cnblogs.com/berylqliu/p/6261498.html