描述
输入一系列整数,建立二叉排序树,并进行前序,中序,后序遍历。
输入描述:
输入第一行包括一个整数n(1<=n<=100)。 接下来的一行包括n个整数。
输出描述:
可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。 每种遍历结果输出一行。每行最后一个数据之后有一个换行。 输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。
示例1
输入:
5
1 6 5 9 8
输出:
1 6 5 9 8
1 5 6 8 9
5 8 9 6 1
代码如下:
java
/*
* 二叉排序树:
* 二叉排序树的创建
*/
import java.util.Scanner;
public class BinarySortTree2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
int n = scanner.nextInt();
//初始化根结点
TreeNode00 root = new TreeNode00(scanner.nextInt());
for (int i = 0; i < n-1; i++) {
createTree(root, scanner.nextInt());
}
preOrder(root);
System.out.println();
inOrder(root);
System.out.println();
postOrder(root);
}
}
//二叉树的创建
public static void createTree(TreeNode00 root,int value) {
if (value <= root.value) {
if (root.lchild == null) {
root.lchild = new TreeNode00(value);
}else {
createTree(root.lchild, value);
}
}else {
if (root.rChild == null) {
root.rChild = new TreeNode00(value);
}else {
createTree(root.rChild, value);
}
}
}
//中序遍历
public static void inOrder(TreeNode00 root) {
if (root == null) {
return ;
}
inOrder(root.lchild);
System.out.print(root.value+" ");
inOrder(root.rChild);
}
//前序遍历
public static void preOrder(TreeNode00 root) {
if (root == null) {
return;
}
System.out.print(root.value+" ");
preOrder(root.lchild);
preOrder(root.rChild);
}
//后序遍历
public static void postOrder(TreeNode00 root) {
if (root == null) {
return ;
}
postOrder(root.lchild);
postOrder(root.rChild);
System.out.print(root.value+" ");
}
}
class TreeNode00{
int value;
TreeNode00 lchild;
TreeNode00 rChild;
public TreeNode00(int value) {
this.value = value;
}
}