Recursion tips

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ๅ€‹ๆ–นๅ‘็š„้žๆญธ๏ผ‰

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

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

Last updated