FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/606_Construct_String_from_Binary_Tree.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
606_Construct_String_from_Binary_Tree.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
41 lines (32 loc) · 1.25 KB
Breadcrumbs
leetcode
/
java
/
606_Construct_String_from_Binary_Tree.java
Copy path
File metadata and controls
41 lines (32 loc) · 1.25 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
/*
https://leetcode.com/problems/construct-string-from-binary-tree/
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis
pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
Add root node to string and return if no children. Add left subtree surrounded by brackets, hence empty brackets if
no subtree. Return without brackets if no right subtree, else add right subtree surrounded by brackets.
Time - O(n)
Space - O(1)
*/
class
Solution
{
StringBuilder
result
=
new
StringBuilder
();
public
String
tree2str
(
TreeNode
t
) {
helper
(
t
);
return
result
.
toString
();
}
private
void
helper
(
TreeNode
node
) {
if
(
node
==
null
)
return
;
result
.
append
(
Integer
.
toString
(
node
.
val
));
if
(
node
.
left
==
null
&&
node
.
right
==
null
)
return
;
result
.
append
(
'('
);
helper
(
node
.
left
);
result
.
append
(
')'
);
if
(
node
.
right
==
null
)
return
;
result
.
append
(
'('
);
helper
(
node
.
right
);
result
.
append
(
')'
);
}
}
Back
|
FazBrowse Home
|
New Git URL