AdSense

Monday, May 25, 2015

Nested function in Python

I was revisiting tree traversal using Python and I realized that Python has this interesting technique, write a function inside another function:


def preOrderRec2(root):
    rst = []
    
    def recursion(root):
        if root:
            rst.append(root.val)
            recursion(root.left)
            recursion(root.right)
    recursion(root)
    return rst


The above example is a tree preorder traversal, inside the global function is the recursive function we use. The advantage of using the inner function is to avoid global exposure of the inner function, since, in the above example,  recursion() will only be called by preOrderRec2(). Some other advantages can be found here.

Unfortunately Java does not allow you to use such great trick. In Java, we will have to write in this way:


public class Solution {
    public List preorderTraversal(TreeNode root) {
        List rst = new ArrayList();
        preOrder(root, rst);
        return rst;
    }
    public void preOrder(TreeNode root, List rst){
        if (root == null)
            return;
        rst.add(root.val);
        preOrder(root.left, rst);
        preOrder(root.right, rst);
    }
}


No comments:

Post a Comment