Last active
September 28, 2018 16:04
-
-
Save laran/373ceb2d12502c8775991b54ccb07941 to your computer and use it in GitHub Desktop.
Add a value to a Binary Tree.
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 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; | |
}; | |
} |
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
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