0

I have been stuck on solving this task for quite a while. I need to write a recursive function to check whether that every node is smaller than any of its children. Returns true if the binary tree is a min-heap and false otherwise.

What i have so far:

def min_heap(t):
    if t == None:
        return True
    else:
        return t.left.value > t.value and t.right.value > t.value
2
  • "I have been stuck on solving this task for quite a while" - show us what you have Commented May 22, 2015 at 1:21
  • Is that recursive? There is a base case, OK, but there is no call to itself in no point? Commented May 22, 2015 at 1:49

1 Answer 1

1

If it's recursive, that means it should be calling itself. Assuming your min-heap by definition is

every node is smaller than any of its children

def min_heap(t):
    if t == None:
        return True
    if t.left and t.value > t.left.value:
        return False
    if t.right and t.value > t.right.value:
        return False
    return min_heap(t.left) and min_heap(t.right)
Sign up to request clarification or add additional context in comments.

5 Comments

In the second and third if statements, aren't t.left and t.right trees?
yes, if t.left just makes sure that it's not None. Otherwise t.left.value would fail.
ooh ok. So that code is the same as if t.left != None and t.value > t.left.value:?
yes exactly. But you should write that as t.left is not None
Why is it better to write it that way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.