javascript - 请教一下,如何实现一个二元查找树,给定一个中数、节点最大值、最小值,随机生成一个二元查找树
阿神
阿神 2017-04-10 15:50:26
[JavaScript讨论组]

最好用JavaScript或Java实现。

我用Javascript实现了这个二元查找树生成器:

function Tree(root,value){
    Tree.prototype.findMin=function(){
        var tmp=this;
        while (tmp.root!=null&&tmp.root.value>tmp.value){
            tmp=tmp.root;
        }
        if(tmp.root!=null)
        {
            return tmp.root.value;
        }else{
            return min;
        }
    }
    Tree.prototype.findMax=function(){
        var tmp=this;
        while (tmp.root!=null&&tmp.root.value<tmp.value){
            tmp=tmp.root;
        }
        if(tmp.root!=null)
        {
            return tmp.root.value;
        }else{
            return max;
        }
    }
    this.root=root;
    this.value=value;
    var leftValue=null;
    this.left=null;
    var rightValue=null;
    this.right=null;
    if(this.root==null)
    {
        leftValue=Math.floor(Math.random()*(this.value-min));
        rightValue=this.value+1+Math.floor(Math.random()*(max-this.value));
        this.left=new Tree(this,leftValue);
        this.right=new Tree(this,rightValue);
    }
    
    var mmin=this.findMin();
    leftValue=mmin+Math.floor(Math.random()*(this.value-mmin));
    if(leftValue>mmin)
        this.left=new Tree(this,leftValue);
    var mmax=this.findMax();
    rightValue=this.value+Math.floor(Math.random()*(mmax-this.value));
    if(rightValue>this.value)
        this.right=new Tree(this,rightValue);
}
var middle=10;
var min=0;
var max=middle*2;

console.info(new Tree(null,10))
阿神
阿神

闭关修行中......

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号