Java递归模板:
// Java
public void recur(int level, int param) {
// 1、递归终结条件
if (level > MAX_LEVEL) {
// process result
return;
}
// 2、处理当前层逻辑
process(level, param);
// 3、进入到下一层
recur( level: level + 1, newParam);
// 4、清理当前层
}
Java分治、迭代模板:
private static int divide_conquer(Problem problem, ) {
//1、终结者(到了最下面的节点)
if (problem == NULL) {
int res = process_last_result();
return res;
}
//2、处理当前逻辑,准备数据
subProblems = split_problem(problem)
//3、调用自身函数,到下一层(子问题)
res0 = divide_conquer(subProblems[0])
res1 = divide_conquer(subProblems[1])
//4、合并子问题
result = process_result(res0, res1);
return result;
}
DFS代码模板
递归写法
//Java
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> allResults = new ArrayList<>();
if(root==null){
return allResults;
}
travel(root,0,allResults);
return allResults;
}
private void travel(TreeNode root,int level,List<List<Integer>> results){
if(results.size()==level){
results.add(new ArrayList<>());
}
results.get(level).add(root.val);
if(root.left!=null){
travel(root.left,level+1,results);
}
if(root.right!=null){
travel(root.right,level+1,results);
}
}
非递归写法
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;
}