0

I am trying to solve the following problem:

Return the root of a binary search tree t modified to contain only values <= k. (Using the normal BST class where we have an item,left and right)

def prune(t,k):
    if not t:
        return None
    if k < t.item
        while t.item > k:
            t = t.left
    return t

I think I am doing it completely wrong.. Maybe there is some easy recursive way to do it?

Bach
  • 6,145
  • 7
  • 36
  • 61
Mac
  • 123
  • 4

1 Answers1

0

I think you want something like:

def prune(t, k):
    if t is None or t.item > k:
        return None
    t.right = prune(t.right, k)
    return t

This is recursive, and will "prune" when it reaches any None node or node larger than k. As this is a BST, t.item <= k means all nodes in t.left will be too, so we can ignore them.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • that wont work, since if I prune a node smaller that is part of the left subtree, the function will do nothing. e.g BTNode(7, BTNode(4, BTNode(3, None, None), None), BTNode(10, None, None)) , if I pick 5, it will remain unchanged since the value is not in the right subtree. – Mac Apr 15 '14 at 23:15
  • @Mac if you pick `k=5` you won't get anything back, as `7 > 5`! Have you actually tried it out? – jonrsharpe Apr 16 '14 at 11:23