File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change 222
222
* [ 240. Search a 2D Matrix II] ( leetcode-240-Search-a-2D-MatrixII.md )
223
223
* [ 241. Different Ways to Add Parentheses] ( leetcode-241-Different-Ways-to-Add-Parentheses.md )
224
224
* [ 242. Valid Anagram] ( leetcode-242-Valid-Anagram.md )
225
+ * [ 257. Binary Tree Paths] ( leetcode-257-Binary-Tree-Paths.md )
225
226
* [ 更多] ( more.md )
Original file line number Diff line number Diff line change
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
+ 考察的就是二叉树的遍历,很基础的一道题。
You can’t perform that action at this time.
0 commit comments