二叉(查找)排序树(BST)

二叉(查找)排序树(BST):对于二叉排序树的任何一个非叶子节点要求左子节点的值比当前节点的值小,右子节点的值比当前节点的值大

特别说明:若有相同的值,可将该节点放在左子节点或右子节点,尽量避免相同值出现

 1 public class BinarySortTreeDemo {
 2     public static void main(String[] args) {
 3         int[] arr = {7,3,10,12,5,1,9};
 4         BinarySortTree binarySortTree = new BinarySortTree();
 5 
 6         for (int i = 0; i < arr.length; i++) {
 7             binarySortTree.add(new Node(arr[i]));
 8         }
 9 
10 
11         System.out.println("中序遍历二叉排序树");
12         binarySortTree.infixOrder();
13     }
14 
15 
16 }
17 
18 
19 
20 //创建二叉排序树
21 class BinarySortTree{
22     private  Node root;
23     //添加节点的方法
24     public void add(Node node){
25         if (root == null){
26             root = node;//如果root为空则直接让root指向node
27         }else {
28             root.add(node);
29         }
30     }
31     //中序遍历
32     public void infixOrder(){
33         if (root != null){
34             root.infixOrder();
35         }else {
36             System.out.println("当前二叉排序树为空,不能遍历");
37         }
38     }
39 }
40 
41 //创建Node节点
42 class Node{
43     private int value;
44     private Node left;
45     private Node right;
46     public Node(int value){
47         this.value=value;
48     }
49 
50     @Override
51     public String toString() {
52         return "Node{" +
53                 "value=" + value +
54                 '}';
55     }
56 
57     //添加节点的方法
58     //递归的形式添加节点,注意满足二叉排序树的要求
59     public void add(Node node){
60         if (node == null){
61             return;
62         }
63 
64         //判断传入的节点值和当前子树的根节点值的关系
65         if (node.value < this.value){
66             //若当前节点的左子节点为null
67             if (this.left == null){
68                 this.left =node;
69             }else {
70                 //递归向左子树添加
71                 this.left.add(node);
72             }
73         }else{//
74             if (this.right == null){
75                 this.right = node;
76             }else {
77                 //递归的向右子树添加
78                 this.right.add(node);
79             }
80         }
81     }
82     //中序遍历
83     public void infixOrder(){
84         if (this.left != null){
85             this.left.infixOrder();
86         }
87         System.out.println(this);
88         if (this.right != null){
89             this.right.infixOrder();
90         }
91     }
92 }

 

posted @ 2022-04-02 21:33  doremi429  阅读(53)  评论(0编辑  收藏  举报