import java.util.Scanner;
public class BinSort {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int nums = sc.nextInt();
int values[] = new int[nums];
for (int i = 0; i < nums; i++) {
values[i] = sc.nextInt();
}
TowTree root = new TowTree(values[0]);
for (int i = 1; i < values.length; i++) {
root.addBean(new TowTree(values[i]));
}
root.firstRoot();
System.out.println();
root.centerRoot();
System.out.println();
root.lastRoot();
System.out.println();
}
}
static class TowTree {
private TowTree left, right;
private int value;
public TowTree(int value) {
this.value = value;
}
public void addBean(TowTree temp) {
if (temp.value == value)
return;
if (temp.value <= value) {
if (left != null) {
left.addBean(temp);
} else {
left = temp;
}
} else {
if (right != null) {
right.addBean(temp);
} else {
right = temp;
}
}
}
public void firstRoot() {
System.out.print(value + " ");
if (left != null) {
left.firstRoot();
}
if (right != null) {
right.firstRoot();
}
}
public void centerRoot() {
if (left != null) {
left.centerRoot();
}
System.out.print(value + " ");
if (right != null) {
right.centerRoot();
}
}
public void lastRoot() {
if (left != null) {
left.lastRoot();
}
if (right != null) {
right.lastRoot();
}
System.out.print(value + " ");
}
}
}
java实现二叉排序树实现前中后遍历
最新推荐文章于 2021-10-09 11:07:00 发布