Search code examples
pythonrecursiontree

Using preorder traversal go binary tree to store elements in a list


I am trying to write a code to implement pre-order traversal of a binary tree and store element in a list. I am using a helper function called pre_util as defined below;

def pre_util(root, L):
   
    if root is None:
       return
    L.append(root)
    
    pre_util(root.left, L)
    pre_util(root.right, L)
    return L
def preorder(root):
    L = []
    res = pre_util(root, L)
    return res

My only question is regarding returning values in the pre_util function recursive call. Will it make a difference if we replace

pre_util(root.left, L) by L=pre_util(root.left, L) In my knowledge if we use L=pre_util(root.left, L) then the returned value overwrites the value of variable L. But I am not too sure why we see in many solutions just pre_util(root.left, L). Appreciate some feedback/explanation


Solution

  • A function that is returning a single piece of information to its caller passes that information either by returning a value, or by storing it into a data structure passed as an argument. You almost never want to do both: it is very error prone.

    So I would write

    def pre_util(root, L):
        if root is None:
           return
        L.append(root)
        
        pre_util(root.left, L)
        pre_util(root.right, L)
    
    def preorder(root):
        L = []
        pre_util(root, L)
        return L