prepbook
  • Introduction
  • Some common stuff
    • python __repr__
    • HackerRank input tips
  • Data Structures and Algorithms
    • Breadth first search
    • Depth First Search
    • Dijkstra
    • A* Search Algorithm
    • Binary Search
    • python counter
    • Sorting
      • Merge Sort
      • Quick Sort
    • Priority Queue
  • Multiprocessing vs Threading
  • Common Coding
    • Find loop in lin list
    • Maximum sum subarray
  • Coding
    • Valid palindrome
    • Palindrome number
    • Remove duplicates from sorted array
    • Island perimeter
    • Serialize and Deserialize Binary Tree
    • Valid Soduku
    • Word Pattern
    • Word Pattern II
    • Group Anagrams
    • Implement Trie
    • Deep copy list with random node
    • Palindrome Permutation
    • Combination Sum
    • Clone Graph
    • Generate parenthesis
    • Fibonacci Number
    • LRU Cache
    • Merge two sorted arrays in place
    • Hamming Distance
    • Merge K sorted arrays
    • Kth smalles element in BST
    • Kth largest element in an array
    • Remove duplicates from sorted list
    • Power of 2
    • Nested list weight sum
    • SIngle number in a list
    • Factor combinations
    • Delete node from BST
  • hacker Rank
    • Coding
      • print staircase
      • Drawing book
      • Challenge 0
      • Min-Max sum
  • WorkRelatedCoding
    • Rectangle Overlap
  • Python tips
Powered by GitBook
On this page

Was this helpful?

  1. Coding

Delete node from BST

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.

  2. If the node is found, delete the node.

Note:Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

    5
   / \
  4   6
 /     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

    5
   / \
  2   6
   \   \
    4   7
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def deleteNode(self, root, key):
        """
        :type root: TreeNode
        :type key: int
        :rtype: TreeNode
        """
        if not root:
            return None

        node, parent = self.lookup(root, key)
        if not node: # some node, which does not even exist in the BST. just return top root
            return root

        '''
        if node:
            print 'node: ', node.val
        if parent:
            print 'parent: ', parent.val
        '''    
        #//////////////////////////////////////////////////////////
        # Case 1: Leaf node. both right = left = None
        #//////////////////////////////////////////////////////////
        if node.right == node.left == None:
            if parent:
                if parent.left == node:
                    parent.left = None
                else:
                    parent.right = None
            else: # top root node having 0 chidren
                return None

        #//////////////////////////////////////////////////////////
        # Case 2: The node has only 1 child
        #//////////////////////////////////////////////////////////
        elif (node.left and node.right is None) or (node.right and node.left is None):
            if parent:
                if parent.left == node:
                    if node.left:
                        parent.left = node.left
                    else:
                        parent.left = node.right
                else:
                    if node.left:
                        parent.right = node.left
                    else:
                        parent.right = node.right
            else: # top root node having only 1 child
                if node.left:
                    node = node.left
                else:
                    node = node.right

                root = node

        #//////////////////////////////////////////////////////////
        # Case 3: The node has both children - complex case
        #//////////////////////////////////////////////////////////
        elif node.right and node.left:
            p = node
            successor = node.right
            while successor.left:
                p = successor
                successor = successor.left

            # At this stage: reached the leftmost leaf node of the right subtree
            # copy data of successor to node
            node.val = successor.val
            if p.left == successor:
                p.left = successor.right
            else:
                p.right = successor.right


        return root

    #//////////////////////////////////////////////////////////
    # function lookup: Also note, how the parent node is being sent back        
    #//////////////////////////////////////////////////////////
    def lookup(self, root, key, parent=None):

        if not root:
            return None, None

        if key == root.val:
            return root, parent
        elif key < root.val:
            return self.lookup(root.left, key, root)
        else:
            return self.lookup(root.right, key, root)
PreviousFactor combinationsNexthacker Rank

Last updated 5 years ago

Was this helpful?

Ref:

http://www.laurentluce.com/posts/binary-search-tree-library-in-python/comment-page-1/