繁体   English   中英

如何在js中访问函数值

[英]how to access function values in js

我有一个js函数,我正在尝试实现二叉树。 我有一个函数可以创建一个节点,它的左边和右边的孩子,就像这样

bst.prototype.cNode = function (x_) {
    this.node = x_;
    this.left = null;
    this.right = null;
};

var a = new bst(); 
a.cNode(5);

这给了我第一个节点,它是左右。

接下来,我尝试使用当前节点值来推动左/右子级检查,例如大于还是小于该节点

a.pushChild(2);


//
function bst(){

    this.pushChild = function(w_){

        if(w_ < this.node){
            if(this.left == null){
                this.left = new this.cNode(w_);
            }
            else{
                this.pushChild(w_);
            }
        }
        else if(w_ > this.node){
            if(this.right == null){
                this.right = new this.cNode(w_);
            }
            else{

            }
        }

    }


}

这给了我Maximun堆栈错误,因为它在无限循环中被执行,因为它始终与第一个this.node和this.left和this.right进行检查,但是this.left和this.right也具有this.node,ths.left ,this.right我也想与而不是与第一个始终进行检查。

如何检查最新值而不是第一个节点的左,右值?

您在第一个节点上反复调用该函数,而根据需要在左侧或右侧节点上调用它:

this.pushChild = function(w_){

    if(w_ < this.node){
        if(this.left == null){
            this.left = new this.cNode(w_);
        }
        else{
            this.left.pushChild(w_);
        }
    }
    else if(w_ > this.node){
        if(this.right == null){
            this.right = new this.cNode(w_);
        }
        else{
            this.right.pushChild(w_);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM