print all leaves in BST: why there should be two base cases?

Question:

I’m looking at the solution of BST problem, printing all leaves in BST as below:

def printLeaf(root):
  if not root: # why this line of code is needed if the if statement below returns as base case?
    return
  if not root.left and not root.right:
    print(root.val)
    return
  printLeaf(root.left)
  printLeaf(root.right) 

I initially wrote my code without the first base case returning at null value of root. But it thrown an error. In my head, it shouldn’t go below leaf since I returned after printing the node but it wasn’t like that since it went down to null stack and threw NoneType exception.
Adding the first line of the function works but still don’t get it why I need that line of code. Can someone kindly explain why?

Code below not stopping recursion, still going down to null node

if not root.left and not root.right:
    print(root.val)
    return
Asked By: Jenny

||

Answers:

Because root.left and root.right in the last two lines could be None.

Answered By: John Ao

Your conditional branch is triggered only when a node in question has neither left nor right child. If only one child is present like in the 2 cases below, nothing prevents you from trying to process an empty node, i.e. None:

    Node with       |         Node with
right child only    |      left child only
                    |
    Node(1)         |        Node(2)
    /              |         /   
   /               |        /     
 None   Node(2)     |    Node(1)   None

To properly handle these cases you either need to check the child nodes before recursing further, e.g.

def print_leaves(node):
   if node.left is None and node.right is None:
       print(node.value)
   if node.left is not None:
       print_leaves(node.left)
   if node.right is not None:
       print_leaves(node.right)

(which is still technically wrong, since you assume that the initial argument is never None). Or you always check the argument for None first like you already are doing.

Answered By: Alex F
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.