Skip to content

Commit edc5c9a

Browse files
committed
solve 257.二叉树的所有路径
1 parent 4bcd1ca commit edc5c9a

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

zh/257.二叉树的所有路径.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* @lc app=leetcode.cn id=257 lang=java
3+
*
4+
* [257] 二叉树的所有路径
5+
*
6+
* https://leetcode-cn.com/problems/binary-tree-paths/description/
7+
*
8+
* algorithms
9+
* Easy (63.85%)
10+
* Likes: 262
11+
* Dislikes: 0
12+
* Total Accepted: 37.4K
13+
* Total Submissions: 58.6K
14+
* Testcase Example: '[1,2,3,null,5]'
15+
*
16+
* 给定一个二叉树,返回所有从根节点到叶子节点的路径。
17+
*
18+
* 说明: 叶子节点是指没有子节点的节点。
19+
*
20+
* 示例:
21+
*
22+
* 输入:
23+
*
24+
* ⁠ 1
25+
* ⁠/ \
26+
* 2 3
27+
* ⁠\
28+
* ⁠ 5
29+
*
30+
* 输出: ["1->2->5", "1->3"]
31+
*
32+
* 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
33+
*
34+
*/
35+
36+
// @lc code=start
37+
/**
38+
* Definition for a binary tree node.
39+
* public class TreeNode {
40+
* int val;
41+
* TreeNode left;
42+
* TreeNode right;
43+
* TreeNode(int x) { val = x; }
44+
* }
45+
*/
46+
class Solution {
47+
public List<String> binaryTreePaths(TreeNode root) {
48+
List<String> list = new ArrayList<>();
49+
if (root != null) {
50+
dfs(list, "", root);
51+
}
52+
return list;
53+
}
54+
55+
public void dfs(List<String> list, String path, TreeNode root) {
56+
if (root.left == null && root.right == null) {
57+
list.add(path + root.val);
58+
} else {
59+
if (root.left != null) {
60+
dfs(list, path + root.val + "->", root.left);
61+
}
62+
if (root.right != null) {
63+
dfs(list, path + root.val + "->", root.right);
64+
}
65+
}
66+
}
67+
}
68+
// @lc code=end
69+

0 commit comments

Comments
 (0)