Basic
pre in post
Graph -> Tree:
- DFS: preorder inorder postorder
- 实现方式:
- 递归:DFS
- 迭代:Stack
- 实现方式:
- BFS: level order
Thinking Tree Problem
- 遍历方式
- 实现方式
- 套模板
模板
|—-|特点|实现|
Preorder 通用解法 DFS
Inorder BST Stack & DFS
Postorder 子模块 DFS
Level order 层扫 BFS
Preorder 模板
-
通用解法
1
2
3
4
5
6
7public static void (List<Integer> res, TreeNode root) {
if (root == null) return;
// 终止条件
helper(res, root.left);
helper(res, root.right);
} -
双Preorder
1
2
3
4
5
6
7
8public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
if (root.left == null && root.right == null) {
return sum == root.val;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
Inorder 模板
- 二叉搜索树: DFS & Stack
1
2
3
4
5
6public static void (List<Integer> res, TreeNode root) {
if (root == null) return;
helper(res, root.left);
// operation
helper(res, root.right);
}
Level Order 模板
1 |
public static List<List<Integer>> levelOrder(TreeNode root) { |
- DFS 实现 BFS - Level Order 模板
1
2
3
4
5
6
7
8
9public static void (List<List<Integer>> res, TreeNode root, int level) {
if (root == null) return;
if (level >= res.size()) {
res.add(new ArrayList<>());
}
res.get(level).add(root.val);
helper(res, root.left, level + 1);
helper(res, root.right, level + 1);
}
综合
- DFS - Backtracking
- Binary Search
- Graph - Union Find
- DP
近期评论