Created
September 21, 2019 01:32
-
-
Save tianmingzuo/4bcdc7eac75459cf38c53f03aa43d940 to your computer and use it in GitHub Desktop.
Data Structures: Add a New Element to a Binary Search Tree: The method should be called addand it should accept an integer value to add to the tree. Take care to maintain the invariant of a binary search tree: the value in each left child should be less than or equal to the parent value, and the value in each right child should be greater than o…
This file contains hidden or 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
| var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2)); | |
| function Node(value) { | |
| this.value = value; | |
| this.left = null; | |
| this.right = null; | |
| } | |
| function BinarySearchTree() { | |
| this.root = null; | |
| this.add = function(val) { | |
| let newNode = new Node(val); | |
| let currentNode = this.root; | |
| if(!currentNode){ | |
| this.root = newNode; | |
| return; | |
| }else{ | |
| let searchTree = function(currentNode) { | |
| if(val < currentNode.value){ | |
| if(currentNode.left){ | |
| searchTree(currentNode.left); | |
| }else{ | |
| currentNode.left = newNode; | |
| return; | |
| } | |
| }else if(val > currentNode.value){ | |
| if(currentNode.right){ | |
| searchTree(currentNode.right); | |
| }else{ | |
| currentNode.right = newNode; | |
| return; | |
| } | |
| }else{ | |
| return null; | |
| } | |
| }; | |
| searchTree(currentNode); | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment