Last active
January 27, 2019 12:29
-
-
Save hk-skit/cf0e656546daaf4646a3824b8c772848 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BinaryTreeNode } from './BinaryTreeNode'; | |
export class BinaryTree { | |
constructor() { | |
this.root = null; | |
} | |
get isEmpty() { | |
return this.root === null; | |
} | |
add(x) { | |
if (this.isEmpty) { | |
this.root = new BinaryTreeNode(x); | |
} else { | |
this.root.add(x); | |
} | |
return this; | |
} | |
/** | |
* Iterator. Traverses in level order. | |
* | |
* @memberof BinaryTree | |
*/ | |
*[Symbol.iterator]() { | |
const queue = this.isEmpty ? [] : [this.root]; | |
while (queue.length) { | |
const { value, left, right } = queue.shift(); | |
if (left !== null) { | |
queue.push(left); | |
} | |
if (right !== null) { | |
queue.push(right); | |
} | |
yield value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment