2016-11-15 13 views
1

このアルゴリズムは、javascriptのデータ構造とアルゴリズムから見つかりました。挿入メソッドの場合は、ルート(現在および親)への参照が2つあります。私の質問は、なぜ私は現在と親をthis.rootに変更できないのですか?彼らは両方ともthis.rootを指します。私はしかし、リファレンスオブジェクトを使用したJavaScriptのBST

'use strict'; 

var BST = function() { 
    this.root = null; 

//embed _Node inside BST so it comes with when BST is created 
    this._Node = function(data, left, right) { 
    this.data = data; 
    this.count = 1; 
    this.left = left; 
    this.right = right; 
    }; 

    this._Node.prototype.show = function() { 
    return this.data; 
    }; 

    this._Node.prototype.showCount = function() { 
    return this.count; 
    } 
}; 


BST.prototype.insert = function(data) { 
    //use this data for a new node 
    var n = new this._Node(data, null, null); 
    //if root is null, put this new node and its data into root 
    if (this.root === null) { 
    this.root = n; 
    } 
    else { 
    //find a child position for this node 
    var current = this.root; 
    var parent; 
    while (true) { 
     parent = current; 
     if (data < current.data) { 
     current = current.left; 
     if (current === null) { 
      parent.left = n; 
      break; 
     } 
     } 
     else { 
     current = current.right; 
     if (current === null) { 
      parent.right = n; 
      break; 
     } 
     } 
    } 
    } 
}; 

var nums = new BST(); 
nums.insert(23); 
nums.insert(45); 
nums.insert(16); 
nums.insert(37); 
nums.insert(3); 
nums.insert(99); 
nums.insert(22); 

答えて

2

currentは、アルゴリズム全体を通じてthis.rootを参照していないことを行うとき、コードが正しく動作しません。

this.rootとして初期化されますが、すぐにcurrent = current.left;またはcurrent = current.right;に再割り当てされます。その瞬間からは、もはやthis.rootではありません。 this.root.leftまたはthis.root.rightのいずれかです。

whileループの次の反復では、再び割り当てられますが、の子ノードに再割り当てされるため、再びthis.rootになりません。

parentは、最初の繰り返しでのみthis.rootになります。それ以降の各繰り返しでは、parent = current;current is no longer this.root ,won't be this.root`のどちらかで再割り当てされます。

0

parentcurrentnullになると、あなたはノードnの目標位置を発見した、あなたはそれを割り当てる必要があり、新しいノードnを作成し、これがツリーに位置だ見つけ、ちょうど前のノードの参照を保持するために使用されます子として(leftまたはrightparentノード

関連する問題