简体   繁体   中英

Deleting Parts of Binary Search Tree

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM