Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Binary search tree deleting

'''
        inorder()function time complexity   : O(n)
        insert() function time complexity   : O(n)
        delete() function time complexity   : O(n)
'''

# Python program to delete operation
# in binary search tree(BST)

# A Binary Tree Node
class Node:

    # Constructor to create a new node
    def __init__(self, key):
        self.val = key
        self.left = None
        self.right = None


# A function to do inorder traversal
def inorder(root):
    if root is not None:
        inorder(root.left)
        print(root.val, end=' ')
        inorder(root.right)


# A function to insert a new node
def insert(root, key):
    # if the tree is empty, return a new node
    if root is None:
        return Node(key)

    # otherwise recur down the tree
    if root.val < key:
        root.right = insert(root.right, key)
    else:
        root.left = insert(root.left, key)

    return root


# A function min key value found in that tree
def minValueNode(root):
    while root.left is not None:
        root = root.left

    return root


# Given a binary search tree and a key, this function
# delete the key and returns the new root
def deleteNode(root, key):
    # Base case
    if root is None:
        return root

    # if the key to be deleted is smaller than the root's
    # key then it lies in left subtree
    if root.val > key:
        root.left = deleteNode(root.left, key)

    # if the key to be delete is greater then the root's key
    # then it lies in right subtree
    elif root.val < key:
        root.right = deleteNode(root.right, key)

    else:

        # Node with only child or no child
        if root.left is None:
            temp = root.right
            root = None
            return temp

        elif root.right is None:
            temp = root.left
            root = None
            return temp

        # Node with two children Get teh inorder successor
        # smallest in the right subtree
        temp = minValueNode(root.right)

        # Copy the inorder successor's content to this node
        root.val = temp.val

        # Delete the inorder successor
        root.right = deleteNode(root.right, temp.val)

    return root


# Driver program to test above functions
if __name__ == '__main__':
    """ Let us create following BST 
                  50 
               /      
              30      70 
             /      /   
           20   40  60   80
                   /   
                  55
    inorder traversal->[20, 30, 40, 50, 55, 60, 70, 80]
    """
    root = None
    root = insert(root, 80)
    root = insert(root, 50)
    root = insert(root, 30)
    root = insert(root, 55)
    root = insert(root, 20)
    root = insert(root, 40)
    root = insert(root, 70)
    root = insert(root, 60)

    print("Inorder traversal of the given tree")
    inorder(root)

    print("

Delete->50")
    root = deleteNode(root, 50)
    print("Inorder traversal of the modified tree")
    inorder(root)

    print("

Delete->20")
    root = deleteNode(root, 20)
    print("Inorder traversal of the modified tree")
    inorder(root)

    print("

Delete->30")
    root = deleteNode(root, 70)
    print("Inorder traversal of the modified tree")
    inorder(root)
Comment

Deletion in a Binary Tree

# Python3 program to illustrate deletion in a Binary Tree
 
# class to create a node with data, left child and right child.
 
 
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Inorder traversal of a binary tree
 
 
def inorder(temp):
    if(not temp):
        return
    inorder(temp.left)
    print(temp.data, end=" ")
    inorder(temp.right)
 
# function to delete the given deepest node (d_node) in binary tree
 
 
def deleteDeepest(root, d_node):
    q = []
    q.append(root)
    while(len(q)):
        temp = q.pop(0)
        if temp is d_node:
            temp = None
            return
        if temp.right:
            if temp.right is d_node:
                temp.right = None
                return
            else:
                q.append(temp.right)
        if temp.left:
            if temp.left is d_node:
                temp.left = None
                return
            else:
                q.append(temp.left)
 
# function to delete element in binary tree
 
 
def deletion(root, key):
    if root == None:
        return None
    if root.left == None and root.right == None:
        if root.key == key:
            return None
        else:
            return root
    key_node = None
    q = []
    q.append(root)
    temp = None
    while(len(q)):
        temp = q.pop(0)
        if temp.data == key:
            key_node = temp
        if temp.left:
            q.append(temp.left)
        if temp.right:
            q.append(temp.right)
    if key_node:
        x = temp.data
        deleteDeepest(root, temp)
        key_node.data = x
    return root
 
 
# Driver code
if __name__ == '__main__':
    root = Node(10)
    root.left = Node(11)
    root.left.left = Node(7)
    root.left.right = Node(12)
    root.right = Node(9)
    root.right.left = Node(15)
    root.right.right = Node(8)
    print("The tree before the deletion:")
    inorder(root)
    key = 11
    root = deletion(root, key)
    print()
    print("The tree after the deletion;")
    inorder(root)
 
Comment

PREVIOUS NEXT
Code Example
Python :: iterating with index in for loops python 
Python :: how to install dependencies python 
Python :: python int to scientific string 
Python :: User.objects.first() get specific id user in django 
Python :: Django Redirect Depending On Request Method 
Python :: format exponentials python 
Python :: from Player import Player 
Python :: transform dictionary keys python 
Python :: how to get checkbutton from a list 
Python :: upload folder to s3 bucket python 
Python :: pandas unstring list 
Python :: string remove ,replace, length in python 
Python :: mathtext to regular python 
Python :: get diagonals of 2d array 
Python :: how to maximize the screen in selenium 
Python :: make django admin page text box smaller 
Python :: bar chart in python 
Python :: scrape pdf out of link 
Python :: convert png rgba to rgb pyhton 
Python :: Iterate through string in python using for loop 
Python :: all python statements 
Python :: python zip 
Python :: python linear search 
Python :: rename files in python 
Python :: numpy primes 
Python :: binary search tree implementation in python 
Python :: python combine nested for loops 
Python :: ocaml returns the last element of a list 
Python :: {} string python 
Python :: pandas create dataframe from multiple dictionaries 
ADD CONTENT
Topic
Content
Source link
Name
1+7 =