[Java] tree known preamble sequence and the sequence in order to create a binary tree

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;
}

Published 57 original articles · won praise 55 · views 1934

Guess you like

Origin blog.csdn.net/qq_40561126/article/details/104670468