題目1078:二叉樹遍歷(2006年清華大學計算機研究生機試真題)

題目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
****************************************************************/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章