2016-11-15 78 views
1

我在JavaScript中從數據結構和算法中找到了此算法。對於插入方法,有兩個對根的引用(current和parent)。我的問題是,爲什麼我不能將當前和父母都更改爲this.root?他們都指出這一點。當我這樣做,但是BST在javascript中使用引用對象

'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;。從那時起current不再是this.root。它可以是this.root.leftthis.root.right

在while循環的下一次迭代中,它將再次被重新分配,但它永遠不會再次爲this.root,因爲它總是被重新分配給current的子節點。

parent是相似的,僅在第一次迭代時爲this.root。在隨後的每次迭代中,它都被parent = current;重新分配,並且自current is no longer this.root ,父母won't be this.root`要麼。

0

parent只是用來保持前一節點的參考,您可以創建新的節點n,然後找到它在樹中的位置,一旦current成爲null,你已經找到了目標位置爲節點n,你需要給它分配作爲子女(leftright)至parent節點