簡體   English   中英

JavaScript:如何實現二叉搜索樹

[英]JavaScript: How to implement Binary Search Tree

我在 JavaScript 中實現二叉搜索樹,但是在編寫插入 function 時,發生了一些錯誤(很可能在 RECURSION 中)。

這是我的代碼:

class BinarySearchTree {
  constructor() {
    this.length = 0;
    this.root = null;
  }
  insert(elem) {
    if (!this.root) {
      //If root is null then this is the root.
      this.root = new BSTNode(elem);
    } else {
      let newNode = new BSTNode(elem);
      let myRoot = this.getParent(this.root, elem)
      console.log(myRoot);

      if (myRoot[1] == 'left') myRoot[0].left = newNode;      //Error Line
      else myRoot[0].right = newNode;

      this.nodes.push(newNode);
      this.arr.push(elem);
    }
    this.length++
  }
  getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user

    if (elem < root.value) {
      if (root.left!==null) this.getParent(root.left, elem); 
      else return [root, 'left'];
    } else {
      if (root.right!==null) this.getParent(root.right, elem);
      else return [root, 'right']
    }
  }
}
class BSTNode {
  constructor(val) {
    this.value = val;
    this.left = null; //Left Node
    this.right = null; //Right Node
  }
}

有兩個班級; BinarySearchTreeBSTNode

錯誤:
Uncaught TypeError: Cannot read property '1' of undefined

我找不到錯誤。

請注意,也歡迎其他解決方案來做同樣的事情。

你應該返回this.getParent(root.left, elem);的結果this.getParent(root.right, elem);

getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user

    if (elem < root.value) {

      if (root.left!==null) return this.getParent(root.left, elem); 
      else return [root, 'left'];
    } else {
      if (root.right!==null) return this.getParent(root.right, elem);
      else return [root, 'right']
    }
  }

它應該是:

getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user

    if (elem < root.value) {
      if (root.left!==null) return this.getParent(root.left, elem); 
      else return [root, 'left'];
    } else {
      if (root.right!==null) return this.getParent(root.right, elem);
      else return [root, 'right']
    }
  }

在不返回這些值的情況下,它將完成查找節點的工作,但不會返回它。 大多數遞歸函數都返回自己,例如: function foo(){return foo()}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM