题目1078:二叉树遍历
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:2251
解决:1347
-
题目描述:
-
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
-
输入:
-
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
-
输出:
-
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
提示:解决方案是先序遍历每次遍历根节点,即先序遍历第一个元素为根,从中序遍历中可以通过根节点来拆分成左子树和右子树,在分别对左子树和右子树进行拆分。
-
样例输入:
-
ABC BAC FDXEAG XDEFAG
-
样例输出:
-
BCA XEDGAF
import java.util.Scanner; public class Main{ /** * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while( scanner.hasNext() ){ String preStr = scanner.nextLine(); String inStr = scanner.nextLine(); Node tree = null; char pre[] = preStr.toCharArray(); char in[] = inStr.toCharArray(); tree = recoverTree(tree,pre,in,0,pre.length-1,0,in.length-1); postPrintf(tree); System.out.println(); } } public static void postPrintf(Node tree){ if(tree.getlChild() != null){ postPrintf(tree.getlChild()); } if(tree.getrChild() != null){ postPrintf(tree.getrChild()); } System.out.print(tree.getKey()); } public static Node recoverTree(Node tree, char pre[],char in[],int s1, int e1, int s2, int e2){ tree = new Node(); tree.setKey(pre[s1]); int idx = -1; for (int i = 0; i < in.length; i++) { if(pre[s1] == in[i]){ idx = i; break; } } if(idx != s2){ tree.setlChild(recoverTree(tree.getlChild(), pre, in, s1+1, s1+idx-s2, s2, idx-1)); } if(idx != e2){ tree.setrChild(recoverTree(tree.getrChild(), pre, in, s1+idx-s2+1, e1, idx+1, e2)); } return tree; } public static class Node{ Node lChild; Node rChild; char key; public Node getlChild() { return lChild; } public void setlChild(Node lChild) { this.lChild = lChild; } public Node getrChild() { return rChild; } public void setrChild(Node rChild) { this.rChild = rChild; } public char getKey() { return key; } public void setKey(char key) { this.key = key; } } } /************************************************************** Problem: 1078 User: yihukurama Language: Java Result: Accepted Time:80 ms Memory:15492 kb ****************************************************************/