标签:
package algorithm01; import java.util.Scanner; /** * 给出先序遍历和中序遍历序列求出二叉树的后续遍历序列 * @author wxisme * */ public class ToReverse { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s1, s2; while(scan.hasNext()) { s1 = scan.next(); s2 = scan.next(); build(s1.length(), 0, 0, s1, s2); } } public static void build(int n, int s1_at, int s2_at, String s1, String s2) { if(n <= 0) return; //求出根节点在中序遍历中的位置 int p = s2.indexOf(s1.charAt(s1_at)) - s2_at; //后续遍历左子树 build(p, s1_at+1, s2_at, s1, s2); //后续遍历右子树 build(n-p-1, s1_at+p+1, s2_at+p+1, s1, s2); //访问根节点 System.out.print(s1.charAt(s1_at)); } }
测试:
DBACEGF ABCDEFG
ACBFGED
BCAD CBAD
CDAB
标签:
原文地址:http://www.cnblogs.com/wxisme/p/4430399.html