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 ListpreorderTraversal(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