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;
}
[Java]已知树的前序序列和中序序列创建二叉树
最新推荐文章于 2023-05-07 16:17:22 发布