> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/recursion-tips.md).

# 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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/recursion-tips.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
