二叉搜索树

作者: 我犟不过你 | 来源:发表于2020-10-27 17:37 被阅读0次

    详细定义参考如下:https://baike.baidu.com/item/%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91
    数据结构学习网站:
    https://www.cs.usfca.edu/~galles/visualization/Algorithms.html

    性质:

    1.若任意结点的左子树不空,则左子树上所有结点的值均不大于它的根结点的值。

    1. 若任意结点的右子树不空,则右子树上所有结点的值均不小于它的根结点的值。
      3.任意结点的左、右子树也分别为二叉搜索树。

    java实现一个二叉搜索树:

    package com.cloud.bssp.indexing;
    
    import org.apache.commons.lang3.ObjectUtils;
    import org.apache.commons.lang3.RandomUtils;
    
    /**
     * 二叉搜索树
     * @date: 2020/10/27
     * @author weirx
     * @version 3.0
     */
    public class BinarySearchTree {
    
        private static class Node {
            int data;
            Node left;
            Node right;
        }
    
        /**
         * 根节点
         */
        private static Node root;
    
        public static void insert(int data) {
            //最终树
            Node result;
            //得到一个节点
            Node node = new Node();
            node.data = data;
            //判断当前根节点是否为空
            if (ObjectUtils.isEmpty(root)) {
                //空?
                root = node;
            } else {
                //非空?
                //初始化一个当前节点,用于后面循环增加节点
                Node current = root;
                while (true) {
                    result = current;
                    if (data >= current.data) {
                        //添加到右侧
                        current = current.right;
                        if (ObjectUtils.isEmpty(current)) {
                            result.right = node;
                            return;
                        }
                    } else {
                        //添加到左侧
                        current = current.left;
                        if (ObjectUtils.isEmpty(current)) {
                            result.left = node;
                            return;
                        }
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            int num;
            for (int i = 0; i < 10; i++) {
                num = RandomUtils.nextInt(0, 10);
                BinarySearchTree.insert(num);
                System.out.println(num);
            }
            //没实际意义,用于打个断点观察root
            System.out.println();
        }
    }
    

    相关文章

      网友评论

        本文标题:二叉搜索树

        本文链接:https://www.haomeiwen.com/subject/ksqxvktx.html