Python Example – Write a Python program to delete a node with the given key in a given Binary search tree (BST)

Hits: 6

(Python Example for Citizen Data Scientist & Business Analyst)

 

Write a Python program to delete a node with the given key in a given Binary search tree (BST).

Note: Search for a node to remove. If the node is found, delete the node.

 

Sample Solution:

Python Code:


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

def delete_Node(root, key):

	if not root: 
		return root

	if root.val > key: 
		root.left = delete_Node(root.left, key)

	elif root.val < key: 
		root.right= delete_Node(root.right, key)

	else: 

		if not root.right:
			return root.left

		if not root.left:
			return root.right

		temp_val = root.right
		mini_val = temp_val.val
		while temp_val.left:
			temp_val = temp_val.left
			mini_val = temp_val.val

		root.right = deleteNode(root.right,root.val)
	return root

def preOrder(node): 
    if not node: 
        return      
    print(node.val)
    preOrder(node.left) 
    preOrder(node.right)   
    
root = TreeNode(5)  
root.left = TreeNode(3)  
root.right = TreeNode(6) 
root.left.left = TreeNode(2)  
root.left.right = TreeNode(4) 
root.left.right.left = TreeNode(7)  
print("Original node:")
print(preOrder(root))
result = delete_Node(root, 4)
print("After deleting specified node:")
print(preOrder(result))

Sample Output:

Original node:
5
3
2
4
7
6
None
After deleting specified node:
5
3
2
7
6
None

 

Write a Python program to delete a node with the given key in a given Binary search tree (BST)

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.