問題描述:輸入某二叉樹的前序遍歷和中序遍歷的結果,得到后序遍歷。
eg :輸入樣例:
DBACEGF ABCDEFG
BCAD CBAD
輸出樣例:
ACBFGED
CDAB

import java.util.Scanner; class TNode { public char value; public TNode(char s) { this.value = s; } } /** * 根據先序和中序得到后序 * @author NEU-2015 * */ public class Demo { public static void main(String[] args) { Scanner input = new Scanner(System.in); String str; String FirstOrder; //先序序列 String InOrder; //中序序列 String Last_String; //后序序列 while(input.hasNext()) { Last_String = ""; str = input.nextLine(); FirstOrder = str.split(" ")[0]; InOrder = str.split(" ")[1]; System.out.println(get_AfterOrder(FirstOrder, InOrder, 0, FirstOrder.length()-1, 0, InOrder.length()-1)); } } public static int count = 0; public static String get_AfterOrder(String FirstOrder, String InOrder, int first_Start, int first_End, int in_Start, int in_End) { String Last_String = ""; //后續序列字符 count++; TNode tree = new TNode(FirstOrder.charAt(first_Start)); if(first_Start == first_End && in_Start == in_End) { //表示該二叉樹只有一個字符 return String.valueOf(tree.value); //返回僅有的一個字符 } int root = 0; //查找根節點在中序遍歷中的位置 for(root = in_Start; root <= in_End; root++) { if(FirstOrder.charAt(first_Start) == InOrder.charAt(root)) { break; } } int next_leftChildTree_length = root - in_Start; //左子樹長度 int next_rightChildTree_length = in_End - root; //右子數長度 if(next_leftChildTree_length > 0) { //遞歸左子樹 Last_String += get_AfterOrder(FirstOrder, InOrder, first_Start+1, first_Start+next_leftChildTree_length, in_Start, root-1); } if(next_rightChildTree_length > 0) { //遞歸右子樹 Last_String += get_AfterOrder(FirstOrder, InOrder, first_Start+1+next_leftChildTree_length, first_End, root+1, in_End); } Last_String += String.valueOf(FirstOrder.charAt(first_Start)); //加上根節點 return Last_String; } }
