二叉树——求最大节点和最小节点

function Node(value,left,right){
    this.value = value;
    this.left=left;
    this.right=right;
}

function Tree(){
    this.root = null;
}
//二叉树代码实现,添加节点
Tree.prototype.add=function(value){
    //判断树有没有根节点
    let node = new Node(value,null,null);
    if(this.root==null){
        //没有根节点 新创建的节点作为树的根节点
        this.root=node;
        return ;
    }else{
        let currentNode = this.root;
        let parentNode =null;
        while(true){
            if(value<currentNode.value){
                parentNode=currentNode;//父节点指向currentNode
                currentNode=currentNode.left;//currentNode往下移动
                if(currentNode==null){//如果currentNode指向空了 那么就需要把节点挂到这个位置
                    parentNode.left=node;
                    break;
                }

            }else if(value>currentNode.value){
                parentNode = currentNode;
                currentNode=currentNode.right;
                if (!currentNode) {
                    parentNode.right = node;
                    break;
                }
            }else{
                break;
            }
        }
    }
}

求最大节点

Tree.prototype.getMaxNode=function(){
    if(this.root==null){
        return;
    }
    let currentNode = this.root;
    while(currentNode.right){
        currentNode=currentNode.right;
    }
    return currentNode;
}

求最小节点

Tree.prototype.getMinNode=function(){
    if(this.root==null){
        return;
    }
    let currentNode = this.root;
    while(currentNode.left){
        currentNode=currentNode.left;
    }
    return currentNode;
}

查找value对应的节点,找到则返回节点,没找到则返回null

Tree.prototype.search=function(value){
    if(this.root==null){
        return null;
    }
    let currentNode = this.root;
    while(currentNode&&currentNode.value!=value){
        if(value<currentNode.value){
            currentNode=currentNode.left;
        }else{
            currentNode=currentNode.right;
        }
    }
    return currentNode;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值