Sunday, 20 March 2016

Week 9 SLOG - Binary Tree

Binary Trees are a special kind of Tree that can only have up to two children. This restriction allows interesting applications such as Binary Search Trees and also makes us have to deal with the code of Binary Trees in a different way.

One thing to note is that Binary Trees can truly be None unlike standard Trees. So we have to check.


In general, we write Binary Tree functions as:

def binary_tree_function(tree):
   if tree is not None:
       # We need to check
       if tree.left is None and tree.right is None:
           # This is a leaf. Do something
       else:
             # Do recursion
             left = tree_function(tree.left, foo)
             # Sometimes we have to do something for the current node too. Do it between the two!
             right = tree_function(tree.right, foo)
   else:
       # Return something appropriate for None

No comments:

Post a Comment