How to adjust a function to initialise array in body rather than argument of function?

Viewed 19

I have a recursive function to traverse a tree using in-order traversal.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def IN_DFS(node, result=[]):
        if not node:
            return result
        Solution.IN_DFS(node.left, result)
        result.append(node.val)
        Solution.IN_DFS(node.right, result)
        return result

I am not a big fan (and I know it is bad practice) to have mutable objects in the argument of functions- as we have above

My question is, how can I rewrite the above code using something like:

def IN_CFS(node): 
    result = [] 
    ...
1 Answers

You can use None as default value, and then initialize it :

def IN_DFS(node, result=None):
    if result is None:
        result = []
    if not node:
        return result
    Solution.IN_DFS(node.left, result)
    result.append(node.val)
    Solution.IN_DFS(node.right, result)
    return result
Related