Skip to content

Instantly share code, notes, and snippets.

@hk-skit
Last active January 27, 2019 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hk-skit/cf0e656546daaf4646a3824b8c772848 to your computer and use it in GitHub Desktop.
Save hk-skit/cf0e656546daaf4646a3824b8c772848 to your computer and use it in GitHub Desktop.
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