特点:
若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
左、右子树也分别为二叉排序树,这点很重要,

代码:
1 package Tree;
2
3 public class SortTree {
4 public static void main(String[] args) {
5 //添加
6 int array[] = {1,4,6,2,8,3,12,90,45,32,89};
7 BinarySortTree binarySortTree = new BinarySortTree();
8 //循环添加结点
9 for (int i = 0 ; i < array.length ; i++){
10 binarySortTree.addNode(new Node(array[i]));
11 }
12
13 //中序遍历
14 binarySortTree.preOrder();
15 }
16 }
17 class BinarySortTree{
18 //根结点
19 private Node root;
20
21 public void setRoot(Node root) {
22 this.root = root;
23 }
24
25 //添加结点
26 public void addNode(Node node){
27 if (this.root == null){
28 root = node;
29 }else {
30 this.root.addNode(node);
31 }
32 }
33
34 //先序遍历
35 public void preOrder(){
36 if (this.root != null){
37 this.root.preOrder();
38 }else {
39 System.out.println("空树");
40 }
41 }
42 }
43 class Node{
44 int value;//结点的值
45 Node left;//左子树
46 Node right;//右子树
47 public Node(int value) {
48 this.value = value;
49 }
50 @Override
51 public String toString() {
52 return "Node{" +
53 "value=" + value +
54 '}';
55 }
56 //添加结点
57 public void addNode(Node node){
58 if (node == null){
59 return;
60 }
61 if (node.value < this.value){
62 if (this.left == null){
63 this.left = node;
64 }else {
65 this.left.addNode(node);
66 }
67 }
68 else {
69 if (node.value > this.value){
70 if (this.right == null){
71 this.right = node;
72 }else {
73 this.right.addNode(node);
74 }
75 }
76 }
77 }
78
79 //前序遍历
80 public void preOrder() {
81 //输出root结点
82 System.out.println(this);
83 if (this.left != null) {
84 this.left.preOrder();//递归左子结点
85 }
86 if (this.right != null) {
87 this.right.preOrder();
88 }
89 }
90 }