Java递归模板:

  1. // Java
  2. public void recur(int level, int param) {
  3. // 1、递归终结条件
  4. if (level > MAX_LEVEL) {
  5. // process result
  6. return;
  7. }
  8. // 2、处理当前层逻辑
  9. process(level, param);
  10. // 3、进入到下一层
  11. recur( level: level + 1, newParam);
  12. // 4、清理当前层
  13. }

image.png

Java分治、迭代模板:

  1. private static int divide_conquer(Problem problem, ) {
  2. //1、终结者(到了最下面的节点)
  3. if (problem == NULL) {
  4. int res = process_last_result();
  5. return res;
  6. }
  7. //2、处理当前逻辑,准备数据
  8. subProblems = split_problem(problem)
  9. //3、调用自身函数,到下一层(子问题)
  10. res0 = divide_conquer(subProblems[0])
  11. res1 = divide_conquer(subProblems[1])
  12. //4、合并子问题
  13. result = process_result(res0, res1);
  14. return result;
  15. }

DFS代码模板

递归写法

  1. //Java
  2. public List<List<Integer>> levelOrder(TreeNode root) {
  3. List<List<Integer>> allResults = new ArrayList<>();
  4. if(root==null){
  5. return allResults;
  6. }
  7. travel(root,0,allResults);
  8. return allResults;
  9. }
  10. private void travel(TreeNode root,int level,List<List<Integer>> results){
  11. if(results.size()==level){
  12. results.add(new ArrayList<>());
  13. }
  14. results.get(level).add(root.val);
  15. if(root.left!=null){
  16. travel(root.left,level+1,results);
  17. }
  18. if(root.right!=null){
  19. travel(root.right,level+1,results);
  20. }
  21. }

非递归写法


BFS代码模板

//Java
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> allResults = new ArrayList<>();
    if (root == null) {
        return allResults;
    }
    Queue<TreeNode> nodes = new LinkedList<>();
    nodes.add(root);
    while (!nodes.isEmpty()) {
        int size = nodes.size();
        List<Integer> results = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            TreeNode node = nodes.poll();
            results.add(node.val);
            if (node.left != null) {
                nodes.add(node.left);
            }
            if (node.right != null) {
                nodes.add(node.right);
            }
        }
        allResults.add(results);
    }
    return allResults;
}