Program to remove all nodes from BST which are not in range in Python

Suppose we have a BST, an two values low and high, we have to delete all nodes that are not between [low, high] (inclusive).

So, if the input is like

low = 7 high = 10, then the output will be

To solve this, we will follow these steps −

  • Define a function solve() . This will take root, low, high
  • if root is null, then
    • return
  • if low > data of root, then
    • return solve(right of root, low, high)
  • if high
  • return solve(left of root, low, high)
  • right of root := solve(right of root, low, high)
  • left of root := solve(left of root, low, high)
  • return root
  • Let us see the following implementation to get better understanding −

    Example

    class TreeNode:
       def __init__(self, data, left = None, right = None):
          self.data = data
          self.left = left
          self.right = right
    def print_tree(root):
       if root is not None: print_tree(root.left)
          print(root.data, end = ', ') print_tree(root.right)
    class Solution:
       def solve(self, root, low, high):
          if not root:
             return
          if low > root.data:
             return self.solve(root.right,low,high)
          if high 

    Input

    root = TreeNode(5)
    root.left = TreeNode(1)
    root.right = TreeNode(9)
    root.right.left = TreeNode(7)
    root.right.right = TreeNode(10)
    root.right.left.left = TreeNode(6)
    root.right.left.right = TreeNode(8)
    low = 7
    high = 10

    Output

    7, 8, 9, 10,
    Updated on: 2020-10-06T05:56:14+05:30

    236 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements