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