Skip to content

Commit 41c5245

Browse files
committed
257
1 parent e9b9d6d commit 41c5245

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,4 +222,5 @@
222222
* [240. Search a 2D Matrix II](leetcode-240-Search-a-2D-MatrixII.md)
223223
* [241. Different Ways to Add Parentheses](leetcode-241-Different-Ways-to-Add-Parentheses.md)
224224
* [242. Valid Anagram](leetcode-242-Valid-Anagram.md)
225+
* [257. Binary Tree Paths](leetcode-257-Binary-Tree-Paths.md)
225226
* [更多](more.md)

leetcode-257-Binary-Tree-Paths.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# 题目描述(简单难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/257.jpg)
4+
5+
输出从根到叶子节点的所有路径。
6+
7+
# 思路分析
8+
9+
很明显是一个二叉树遍历的问题,我们可以用递归形式的 `DFS` ,使用栈形式的 `DFS`,使用队列形式的 `BFS`
10+
11+
[112 题](https://leetcode.wang/leetcode-112-Path-Sum.html) 差不多,这里就不详细说了。
12+
13+
只给出 `DFS` 递归的代码了,其他代码的话可以参考 [这里](https://leetcode.com/problems/binary-tree-paths/discuss/68278/My-Java-solution-in-DFS-BFS-recursion)
14+
15+
# 解法一 DFS
16+
17+
`result` 保存所有解,到达叶子节点的时候就将结果保存起来。
18+
19+
```java
20+
public List<String> binaryTreePaths(TreeNode root) {
21+
List<String> result = new ArrayList<>();
22+
if(root == null){
23+
return result;
24+
}
25+
binaryTreePaths(root, "", result);
26+
return result;
27+
}
28+
29+
private void binaryTreePaths(TreeNode root, String temp, List<String> result) {
30+
if (root.left == null && root.right == null) {
31+
temp = temp + root.val;
32+
result.add(temp);
33+
return;
34+
}
35+
if (root.left != null) {
36+
binaryTreePaths(root.left, temp + root.val + "->", result);
37+
}
38+
if (root.right != null) {
39+
binaryTreePaths(root.right, temp + root.val + "->", result);
40+
}
41+
}
42+
```
43+
44+
#
45+
46+
考察的就是二叉树的遍历,很基础的一道题。

0 commit comments

Comments
 (0)