【发布时间】:2021-10-16 20:26:20
【问题描述】:
BinarySearchTree.prototype.height = function () {
if (this.right === null && this.left === null) return 1;
var heightLeft = 0;
var heightRight = 0;
if (this.left != null)
heightLeft = this.height(this.left);
if (this.right != null)
heightRight =this.height(this.right);
if (heightLeft > heightRight) {
return heightLeft + 1;
} else {
return heightRight + 1;
}
};
我需要获取 BST 的高度。我理解这个理论,但我希望根算作 1 而不是 0。
如果我有这样的 BST:
16 ---> lvl1
/ \
6 23 ---> lvl2
/ \ / \
2 14 17 31 ---> lvl3
\
5 ---> lvl4
...那么高度将是 4.
我的函数遇到堆栈溢出。我怎样才能让它发挥作用?
【问题讨论】:
-
你的构造函数
BinarySearchTree是什么样的?
标签: javascript search tree binary binary-search-tree