FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaArithmetic/src/LeetCode/LeetCode257.java at master · git-jhy/JavaArithmetic · GitHub
git-jhy
JavaArithmetic
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode257.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
63 lines (50 loc) · 1.49 KB
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode257.java
Copy path
File metadata and controls
63 lines (50 loc) · 1.49 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
;
}
}
Back
|
FazBrowse Home
|
New Git URL