Data Structures: Add a New Element to a Binary Search Tree
This commit is contained in:
		
							parent
							
								
									5e17d76817
								
							
						
					
					
						commit
						f74eb15489
					
				
							
								
								
									
										35
									
								
								Data Structures/bstAddElement.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										35
									
								
								Data Structures/bstAddElement.js
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,35 @@
 | 
			
		||||
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/add-a-new-element-to-a-binary-search-tree
 | 
			
		||||
 | 
			
		||||
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;
 | 
			
		||||
  // Only change code below this line
 | 
			
		||||
  this.add = (item) => {
 | 
			
		||||
    const newNode = new Node(item);
 | 
			
		||||
    if (this.root === null) {
 | 
			
		||||
      this.root = newNode;
 | 
			
		||||
    }
 | 
			
		||||
    let parentNode = null;
 | 
			
		||||
    let nodeBranch = "left";
 | 
			
		||||
    let node = this.root;
 | 
			
		||||
    while (node !== null) {
 | 
			
		||||
      parentNode = node;
 | 
			
		||||
      if (node.value == item) {
 | 
			
		||||
        return null;
 | 
			
		||||
      } else if (node.value < item) {
 | 
			
		||||
        nodeBranch = "right";
 | 
			
		||||
        node = node.right;
 | 
			
		||||
      } else {
 | 
			
		||||
        nodeBranch = "left";
 | 
			
		||||
        node = node.left;
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
    parentNode[nodeBranch] = newNode;
 | 
			
		||||
  };
 | 
			
		||||
  // Only change code above this line
 | 
			
		||||
}
 | 
			
		||||
		Loading…
	
		Reference in New Issue
	
	Block a user