簡體   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