查找树的最大节点、最小节点


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.getMax = function () {
    if (this.root == null) {
        return;
    }
    let currentNode = this.root;
    while (currentNode.right) {
        currentNode = currentNode.right;
    }
    return currentNode;
}

求最小节点

Tree.prototype.getMin = 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;
    //如果currentNode指向得值不为空 且对应得value值和要找得值不相同
    while (currentNode && currentNode.value != value) {
        //如果value比节点得值小 ,那么currentNode 指向 当前节点得左节点
        if (value < currentNode.value) {
            currentNode = currentNode.left;
        } else {
            // //如果value比节点得值小 ,那么currentNode 指向 当前节点得右节点
            currentNode = currentNode.right;
        }
    }
    return currentNode;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值