[Java]已知樹的前序序列和中序序列創建二叉樹

package tree;

import java.util.Arrays;
import java.util.Scanner;

public class GetTree {

    public static Note2 getTree(String pre,String cen) {
        if(pre.length() == 0 || cen.length() == 0) return null;
        char ch = pre.charAt(0);
        int i = cen.indexOf(ch);
        String cenl = cen.substring(0,i);
        String cenr = cen.substring(i + 1);
        String prel = pre.substring(1,i + 1);
        String prer = pre.substring(i + 1);
        Note2 t = new Note2();
        t.data = ch;
        t.lChild = getTree(prel,cenl);
        t.rChild = getTree(prer,cenr);
        return t;
    }
    /*
    * 先序
    * */
    public static void preShow (Note2 t) {
        if (t == null) return;
        System.out.print(t.data);
        preShow(t.lChild);
        preShow(t.rChild);
    }
    /*
    * 中序
    * */
    public static void cenShow(Note2 t) {
        if (t == null) return;
        cenShow(t.lChild);
        System.out.print(t.data);
        cenShow(t.rChild);
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String pre = sc.next();   //先序遍歷序列
        String cen = sc.next();   //中序遍歷序列
        Note2 tree = getTree(pre, cen);
        preShow(tree);
        System.out.println();
        cenShow(tree);
    }
}
class Note2 {
    char data;
    Note2 lChild, rChild;
}

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