1

I need to write a recursion for a min-heap binary tree to check if this tree is min-heap. One of the test cases is just NONE.

Is None considered a min-heap tree and returns True, or None is False?

The reason I am asking is that I will reach leaves at some point and their nodes are None and if base case is True then it will return True.

rypel
  • 4,686
  • 2
  • 25
  • 36

3 Answers3

1

I believe that a none type will be vacuously true as it does not violate the definition of a min-heap tree.

Andrew Malta
  • 850
  • 5
  • 15
  • I saw somewhere in wikipedia that it is sort of considered True, but can't convince myself and I am uncertain. Thank you. I will create my function under assumption that just: tree = None will return True. – user3029334 May 16 '15 at 18:58
0

Yes, None is considered a mean-heap tree.

shruti1810
  • 3,920
  • 2
  • 16
  • 28
0

You must mean a Min Heap. When we are dealing with any tree structure the children of a Node are most commonly initialized as None. One of the reasons is that we can easily escape the recursion as such:

def find_node(node, data):
   if root is None:
      return
   if root.data == data:
       print "Node found"
   find_node(node.left, data)
   find_node(node.right, data)



class Node(object):

    def __init__(self, data):
       self.left = None
       self.right = None
       self.data = data

In your case you want to check if a tree is min heap by traversing it. You would do something like that

def is_min_heap(root):
  #.....check here and then do
  return is_min_heap(root.left) and is_min_heap(root.right)

But it depends how you want to handle it. Any one node with no children is a min-heap or a max-heap but it has no meaning. If you want to call

is_min_heap(None) then you are free to do so but it is up to you if you want to say that is True or not.

MayTheSchwartzBeWithYou
  • 1,181
  • 1
  • 16
  • 32
  • Thank you. I implemented a function and it works correctly. I was just confused with understanding of a binary tree if I should consider None a tree or not. Once, I knew the answer (I considered a None a True case) recursion was sort of the easiest part to implement. Thank you. – user3029334 May 16 '15 at 20:37