二叉排序樹


特點:

  若左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;

  若右子樹不空,則右子樹上所有結點的值均大於或等於它的根結點的值;

  左、右子樹也分別為二叉排序樹,這點很重要,

 

 

代碼:

 

 

 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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM