forked from forging2012/JavaArithmetic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode257.java
More file actions
63 lines (50 loc) · 1.49 KB
/
LeetCode257.java
File metadata and controls
63 lines (50 loc) · 1.49 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package LeetCode;
import java.util.ArrayList;
import java.util.List;
public class LeetCode257 {
/// 257. Binary Tree Paths
/// https://leetcode.com/problems/binary-tree-paths/description/
/// 时间复杂度: O(n), n为树中的节点个数
/// 空间复杂度: O(h), h为树的高度
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
/**
* 从底一直往上加
* @param root
* @return
*/
public List<String> binaryTreePaths(TreeNode root) {
ArrayList<String> res = new ArrayList<>();
if (root == null)
return res;
// 比如 1
// /
// 2
if (root.left == null && root.right == null) {
res.add(Integer.toString(root.val));
return res;
}
List<String> leftPaths = binaryTreePaths(root.left);
for (String s : leftPaths) {
StringBuilder sb = new StringBuilder(Integer.toString(root.val));
sb.append("->");
sb.append(s);
res.add(sb.toString());
}
List<String> rightPaths = binaryTreePaths(root.right);
for (String s : rightPaths) {
StringBuilder sb = new StringBuilder(Integer.toString(root.val));
sb.append("->");
sb.append(s);
res.add(sb.toString());
}
return res;
}
}