Skip to content

Instantly share code, notes, and snippets.

@laran
Last active September 28, 2018 16:04
Show Gist options
  • Save laran/373ceb2d12502c8775991b54ccb07941 to your computer and use it in GitHub Desktop.
Save laran/373ceb2d12502c8775991b54ccb07941 to your computer and use it in GitHub Desktop.
Add a value to a Binary Tree.
import Node from 'binary-tree-node';
class BinaryTree {
constructor() {
this.root = new Node();
}
// ... other methods
add(value) {
var node = this.root;
if (isUndefined(node.value)) {
node.value = value;
} else {
while (!isUndefined(node)) {
if (isEqualTo(value, node.value)) {
break; // short-circuit duplicate values
} else if (value < node.value) {
if (isUndefined(node.left)) {
node.left = new Node(value);
break;
} else {
node = node.left;
}
} else if (value > node.value) {
if (isUndefined(node.right)) {
node.right = new Node(value);
break;
} else {
node = node.right;
}
}
}
}
return this;
};
}
export default class Node {
constructor(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment