简体   繁体   English

如何在js中访问函数值

[英]how to access function values in js

I have a js function where I am trying to implementing binary tree. 我有一个js函数,我正在尝试实现二叉树。 I have one function which create a node ,it's left and it's right child, like so 我有一个函数可以创建一个节点,它的左边和右边的孩子,就像这样

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

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

This gives me first node and it's left and right. 这给了我第一个节点,它是左右。

Next I am trying to push left/right child check with the current node value whether is greater than node or lesser that node like so 接下来,我尝试使用当前节点值来推动左/右子级检查,例如大于还是小于该节点

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{

            }
        }

    }


}

It is giving me Maximun stack error because it is struck in infinite loop because it is always checking with the first this.node and this.left and this.right but this.left and this.right also has this.node,ths.left,this.right also i want to check with that not with the first one always. 这给了我Maximun堆栈错误,因为它在无限循环中被执行,因为它始终与第一个this.node和this.left和this.right进行检查,但是this.left和this.right也具有this.node,ths.left ,this.right我也想与而不是与第一个始终进行检查。

How can is check with the latest values and not with the first node,left,right values? 如何检查最新值而不是第一个节点的左,右值?

You are repeatedly calling the function on the first node, instead call it on the left or right node, as required: 您在第一个节点上反复调用该函数,而根据需要在左侧或右侧节点上调用它:

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