二叉排序树
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class tree {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
String line;
while ((line=reader.readLine()) != null) {
//readLine()每次读回来的都是一行
int n = Integer.parseInt(line);
//parseInt(String s): 返回用十进制参数表示的整数值
String[] vals = reader.readLine().split(" ");
Node tree = null;
for (int i=0; i< n; i++) {
int x = Integer.parseInt(vals[i]);
tree = insert(tree, x);
}
preOrder(tree);
System.out.println();
inOrder(tree);
System.out.println();
postOrder(tree);
System.out.println();
}
}
//一个递归函数用来插入数
static Node insert(Node root, int x) {
if (root == null) {
root = new Node(x);
return root;
} else if (x < root.val) {
root.left = insert(root.left, x);
} else if (x > root.val) {
root.right = insert(root.right, x);
}
// 忽略数值相等的结点
return root;
}
// 前序遍历
static void preOrder(Node root) {
if (root != null)
System.out.print(root.val+" ");
if (root.left != null) preOrder(root.left);
if (root.right != null) preOrder(root.right);
}
// 中序遍历
static void inOrder(Node root) {
if (root.left != null) inOrder(root.left);
if (root != null)
System.out.print(root.val+" ");
if (root.right != null) inOrder(root.right);
}
// 后序遍历
static void postOrder(Node root) {
if (root.left != null) postOrder(root.left);
if (root.right != null) postOrder(root.right);
if (root != null)
System.out.print(root.val+" ");
}
}
class Node {
Node left;
Node right;
int val;
Node(int val) {
this.val = val;
}
}