【发布时间】:2022-01-25 08:05:39
【问题描述】:
我只是一个初学者,所以如果错误太明显,我很抱歉。
我的两个问题是:
- 我们学校提供的代码中
this.root是什么; - 如何实现
.height方法来测量树的深度。
解释: 我们在课堂上得到了这个代码:
function BinarySearchTree(value) {
this.value = value;
this.right = null;
this.left = null;
}
BinarySearchTree.prototype.add = function(value) {
let newLeaf = new BinarySearchTree(value)
if(value > this.value){
this.right === null? this.right = newLeaf : this.right.add(value)
} else {
this.left === null? this.left = newLeaf : this.left.add(value)
}
};
我们应该写一个方法来计算二叉树的高度/深度。现在,在练习时,我看到了一些奇怪的东西。在创建空二叉树的新节点后,第一个节点最终完全为空,而它继续在第一个空的左侧创建一个新节点。好吧,不是空的,但其值为undefined。这是一种期望的行为吗?
let newTree = new BinarySearchTree
>undefined
newTree.add(7)
>undefined
newTree.add(3)
>undefined
newTree.add(5)
>undefined
newTree
>BinarySearchTree {value: undefined, right: null, left: BinarySearchTree}
left: BinarySearchTree {value: 7, right: null, left: BinarySearchTree}
right: null
value: undefined
[[Prototype]]: Object
现在,考虑到.add 方法的测试通过了,显然我在这种情况下可能是错的,因为这是课堂上老师提供给我们的代码。
这是我一直在网上找到的代码,我对.heigth 方法的代码没有深入了解的原因是因为我无法实现this.root:
function Node(val){
this.value = val;
this.left = null;
this.right = null;
}
function BinarySearchTree(){
this.root = null;
}
我应该如何继续使用.height 方法?
如果有帮助,以下是测试:
describe('Binary Search Tree', function() {
var binarySearchTree;
beforeEach(function() {
binarySearchTree = new BinarySearchTree(5);
});
it('should have methods named "add", "contains", "depthFirstPre", "depthFirstIn", "depthFirstPost", "breadthFirst"', function() {
expect(binarySearchTree.add).to.be.a("function");
});
it('should add values at the correct location in the tree', function(){
binarySearchTree.add(2);
binarySearchTree.add(3);
binarySearchTree.add(7);
binarySearchTree.add(6);
expect(binarySearchTree.left.right.value).to.equal(3);
expect(binarySearchTree.right.left.value).to.equal(6);
});
it('height method should return correct height', function() {
binarySearchTree.left = new BinarySearchTree(3);
binarySearchTree.left.left = new BinarySearchTree(1);
expect(binarySearchTree.height()).to.eql(2);
binarySearchTree.left.left.right = new BinarySearchTree(2);
expect(binarySearchTree.height()).to.eql(3);
binarySearchTree.left.left.left = new BinarySearchTree(0);
expect(binarySearchTree.height()).to.eql(3);
binarySearchTree.right = new BinarySearchTree(8);
expect(binarySearchTree.height()).to.eql(3);
});
}
再次,我为一个很长的问题道歉。我试图写下关于我的问题的所有相关信息。 节日快乐!
【问题讨论】:
-
在 BinarySearchTree.prototype.add 中,应该处理 this.value == null(根节点为 null 时)的情况。
-
"创建一个空二叉树的新节点" - 你们学校提供的第一个数据结构的问题是它不能代表一棵空树.一旦你创建了
new BinarySearchTree,你就会得到一棵树,它由一个值为undefined的节点(根节点)组成。所以是的,从BinarySearchTree中分离出Node的想法是正确的方法。但既然你的老师希望你使用他们的方法,就考虑成为一个NonEmptyBinarySearchTree,它的高度总是至少为 1。 -
@Bergi 感谢您的回复。如果我的 BST 和 Node 没有分开,我应该如何继续写
function height(node){...? -
@jh316 感谢您的回复。很遗憾,我们不允许更改学校提供的代码。
标签: javascript binary-tree nodes