LeetCode 362. Design Hit Counter[Medium]

113. 路径总和 II - 力扣(LeetCode)

题目

方法1:深度优先遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Problem113Solution3 {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();

public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
traversal(root, targetSum);
return result;
}

public void traversal(TreeNode treeNode, int targetSum) {
if (treeNode == null) {
return;
}

path.add(treeNode.val);
targetSum -= treeNode.val;

if (treeNode.left == null && treeNode.right == null && targetSum == 0) {
result.add(new ArrayList<>(path));
}

traversal(treeNode.left, targetSum);
traversal(treeNode.right, targetSum);
path.pollLast();
}

class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {
}

TreeNode(int val) {
this.val = val;
}

TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}

其他关键词

  • 二叉树中和为某一值的路径

相同题目

LCR 153. 二叉树中和为目标值的路径 - 力扣(LeetCode)

剑指 Offer 34

类似题目

参考资料

  1. 剑指 Offer 34. 二叉树中和为某一值的路径_AlgoMooc算法慕课网
  2. 剑指 Offer 34. 二叉树中和为某一值的路径 | 算法通关手册(LeetCode)
  3. 【LeetCode剑指offer34】二叉树中和为某一值的路径(dfs回溯)-阿里云开发者社区