merge: Let traverseLevel return early if node is null (#878)

This commit is contained in:
Worldwidebrine
2022-01-24 17:43:48 +08:00
committed by GitHub
parent 7dd99c1c03
commit 31b06c9abe

View File

@ -19,7 +19,7 @@ class BinaryTree {
breadthFirst () { breadthFirst () {
const h = this.getHeight(this.root) const h = this.getHeight(this.root)
for (let i = 1; i <= h; i++) { for (let i = 0; i !== h; i++) {
this.traverseLevel(this.root, i) this.traverseLevel(this.root, i)
} }
return this.traversal return this.traversal
@ -27,23 +27,23 @@ class BinaryTree {
// Computing the height of the tree // Computing the height of the tree
getHeight (node) { getHeight (node) {
if (node == null) { if (node === null) {
return 0 return 0
} else {
const lheight = this.getHeight(node.left)
const rheight = this.getHeight(node.right)
return lheight > rheight ? lheight + 1 : rheight + 1
} }
const lheight = this.getHeight(node.left)
const rheight = this.getHeight(node.right)
return lheight > rheight ? lheight + 1 : rheight + 1
} }
traverseLevel (node, level) { traverseLevel (node, levelRemaining) {
if (level === 1 && node !== null) { if (node === null) {
return
}
if (levelRemaining === 0) {
this.traversal.push(node.data) this.traversal.push(node.data)
} else { } else {
if (node !== null) { this.traverseLevel(node.left, levelRemaining - 1)
this.traverseLevel(node.left, level - 1) this.traverseLevel(node.right, levelRemaining - 1)
this.traverseLevel(node.right, level - 1)
}
} }
} }
} }