Data Structures: Delete a Node with Two Children in a Binary Search Tree
This commit is contained in:
		
							parent
							
								
									48fd64b61f
								
							
						
					
					
						commit
						1f54446eda
					
				
							
								
								
									
										48
									
								
								Data Structures/bstDeleteTwoChildrenNode.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										48
									
								
								Data Structures/bstDeleteTwoChildrenNode.js
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,48 @@
 | 
			
		||||
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/delete-a-node-with-one-child-in-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.remove = (value) => {
 | 
			
		||||
    let parent = null;
 | 
			
		||||
    let node = this.root;
 | 
			
		||||
    while (node !== null && node.value !== value) {
 | 
			
		||||
      parent = node;
 | 
			
		||||
      if (node.value < value) {
 | 
			
		||||
        node = node.right;
 | 
			
		||||
      } else {
 | 
			
		||||
        node = node.left;
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
    if (node === null) return null;
 | 
			
		||||
    let child = null;
 | 
			
		||||
    if (node.left !== null && node.right === null) child = node.left;
 | 
			
		||||
    else if (node.left === null && node.right !== null) child = node.right;
 | 
			
		||||
    else if (node.left !== null && node.right !== null) {
 | 
			
		||||
      let smallestRightNodeParent = node;
 | 
			
		||||
      let smallestRightNode = node.right;
 | 
			
		||||
      while (smallestRightNode.left !== null) {
 | 
			
		||||
        smallestRightNodeParent = smallestRightNode;
 | 
			
		||||
        smallestRightNode = smallestRightNode.left;
 | 
			
		||||
      }
 | 
			
		||||
      node.value = smallestRightNode.value;
 | 
			
		||||
      if (smallestRightNodeParent !== node)
 | 
			
		||||
        smallestRightNodeParent.left = smallestRightNode.right;
 | 
			
		||||
      else node.right = null;
 | 
			
		||||
      return;
 | 
			
		||||
    }
 | 
			
		||||
    if (parent === null) this.root = child;
 | 
			
		||||
    else if (parent.value < value) {
 | 
			
		||||
      parent.right = child;
 | 
			
		||||
    } else {
 | 
			
		||||
      parent.left = child;
 | 
			
		||||
    }
 | 
			
		||||
  };
 | 
			
		||||
}
 | 
			
		||||
		Loading…
	
		Reference in New Issue
	
	Block a user