前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >二分查找判定树(二分查找树平均查找长度)

二分查找判定树(二分查找树平均查找长度)

作者头像
全栈程序员站长
发布2022-07-27 11:26:50
5030
发布2022-07-27 11:26:50
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

Don’t say much, just go to the code.

代码语言:javascript
复制
package org.bood.tree;

/** * 二分查找树 * ps:如果 data[0] 等于一组数据中最小的,那么就会增加查找的时间复杂度。<br/> * 平衡二叉树(追求极致的平衡),现实需求很难满足,红黑数孕育而生 <br/> * * @author bood * @since 2020/10/16 */
public class BinarySearchTree { 
   

    /** * 根节点数 */
    int data;
    /** * 左边的数 */
    BinarySearchTree left;
    /** * 右边的数 */
    BinarySearchTree rigth;

    public BinarySearchTree(int data) { 
   
        this.data = data;
        this.left = null;
        this.rigth = null;
    }

    // 二分查找
    public void insert(BinarySearchTree root, int data) { 
   
        // 数大于根节点数,右边
        if (data > root.data) { 
   

            // 右边是空的直接插入
            if (null == root.rigth) { 
   
                root.rigth = new BinarySearchTree(data);
            } else { 
   
                insert(root.rigth, data);
            }

            // 数大于根节点数,左边
        } else { 
   

            // 左边是空的直接插入
            if (null == root.left) { 
   
                root.left = new BinarySearchTree(data);
            } else { 
   
                insert(root.left, data);
            }

        }
    }

    // 中序遍历
    public void in(BinarySearchTree root) { 
   
        if (null != root) { 
   
            in(root.left);
            System.out.print(root.data + " ");
            in(root.rigth);
        }
    }

    public static void main(String[] args) { 
   
        int[] data = { 
   5, 6, 1, 7, 8, 9, 2, 4, 10};
        BinarySearchTree root = new BinarySearchTree(data[0]);
        for (int i = 0; i < data.length; i++) { 
   
            root.insert(root, data[i]);
        }

        System.out.println("中序遍历:");
        root.in(root);
    }

}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/128209.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年4月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档