Code Snippets · December 15, 2020

Insert and Delete Operation in Binary Search Tree | Code Snippet | Python

This post is all about code. We will see the implementation of insertion and deletion in the Binary Search Tree. I will try to write details about these topics soon.

TreeNode

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

Insert

def insert(root, val):

	if root is None:
		return TreeNode(val)
	
	curr = root
	
	while curr:
		if val <= curr.val:
			if curr.left is None:
				curr.left = TreeNode(val)
				break
				
			curr = curr.left
		else:
			if curr.right is None:
				curr.right = TreeNode(val)
				break
				
			curr = curr.right
	
	return root

Delete

def delete(root, val):

	if root is None:
		return root
	
	if key < root.val:
		root.left = deleteNode(root.left, key)
	elif key > root.val:
		root.right = deleteNode(root.right, key)
	else:
		
		if root.left is None:
			return root.right
		elif root.right is None:
			return root.left
		
		node = successor(root.right)
		root.val = node.val
		root.right = deleteNode(root.right, node.val)
		
	return root

def successor(root):
	while root.left:
		root = root.left
	
	return root