简体   繁体   中英

how to access function values in js

I have a js function where I am trying to implementing binary tree. 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.

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_);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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