# Recursion tips



```java
public void helper() {

    //terminator
    if (xxxx) {  
        return 
    }
    
    // process
    do something
    
    // drill down, go to next level
    helper(level + 1....)
    
    // reverse state( 有時需要, like backtracking)
}
```



## Example:  94. Binary Tree Inorder Traversal

left  root right  (2個方向的遞歸）

```java
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(root, res);
        return res;
    }
    private void helper(TreeNode root, List<Integer> res) {
        if (root == null) { // terminator
            return;
        }
        
        if (root.left != null) {
            helper(root.left, res);  // drill down
        }
        
        res.add(root.val); // process
        
        if (root.right != null) {
            helper(root.right, res); // drill down
        }
    }
}
```

## Example:  589. N-ary Tree Preorder Traversal

```java
class Solution {
    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        helper(root, res);
        return res;
    }
    private void helper(Node root, List<Integer> res) {
        if (root == null) { // terminator
            return;
        }
        res.add(root.val); // process
        
        for (Node node : root.children) { // drill down, go to next level
            helper(node, res);
        }
    }
}
```

## Backtracking

