2016-11-15 50 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节点