二叉排序树(java实现)

二叉排序树(BST)

二叉搜索树,倒状的树形结构。如下图所示

在这里插入图片描述

特点:

  • 所有的非叶子节点最多拥有两个子节点树(左子树和右子树)。
  • 所有结点存储一个关键字。
  • 节点的左右儿子,左边是比该节点小的,右边是比该节点大的。
package com.zyk;

class Node{
    int value;
    Node left;
    Node rigth;

    public Node(int value){
        this.value=value;
    }
    //添加节点的方法
    public void add(Node node){
        if(node==null){
            return;
        }

        if(node.value<this.value){
            if(this.left==null){
                this.left=node;
            }else{
                //递归让该节点的左子节点去执行add方法
                this.left.add(node);
            }
        }

        if(node.value>this.value){
            if(this.rigth==null){
                this.rigth=node;
            }else{
                //递归让该节点的右子节点去执行add方法
                this.rigth.add(node);
            }
        }
    }

    //中序遍历输出结果
    public void inorder(){
        if(this.left!=null) {
            this.left.inorder();
        }
        System.out.println(this.value);
        if(this.rigth!=null){
            this.rigth.inorder();
        }
    }

}

class BinarySearchTree{
    private Node root;

    public void add(Node node){
        if(root==null){
            root=node;
        }else{
            //每一个node都要去跟root比较
            root.add(node);
        }
    }

    public void inorder(){
        if(root!=null){
            root.inorder();
        }
    }
}

public class BianrySearchTreeDemo {
    public static void main(String[] args) {
        int[] arr={7,3,10,12,5,1,9};
        BinarySearchTree binarySearchTree=new BinarySearchTree();
        //循环添加节点到二叉排序树
        for (int i = 0; i <arr.length ; i++) {
            binarySearchTree.add(new Node(arr[i]));
        }
        //中序遍历出结果
        binarySearchTree.inorder();
    }
}

结果

1
3
5
7
9
10
12
发布了39 篇原创文章 · 获赞 19 · 访问量 1465

猜你喜欢

转载自blog.csdn.net/weixin_44222272/article/details/105564550