Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 917bdf0

Browse files
author
Openset
committed
Add: construct_string_from_binary_tree
1 parent 2d713f4 commit 917bdf0

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

‎problems/construct-string-from-binary-tree/construct_string_from_binary_tree.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package construct_string_from_binary_tree
22

3-
import . "github.com/openset/leetcode/internal/kit"
3+
import (
4+
"strconv"
5+
6+
. "github.com/openset/leetcode/internal/kit"
7+
)
48

59
/**
610
* Definition for a binary tree node.
@@ -11,5 +15,17 @@ import . "github.com/openset/leetcode/internal/kit"
1115
* }
1216
*/
1317
func tree2str(t *TreeNode) string {
14-
return ""
18+
ans := ""
19+
if t != nil {
20+
ans += strconv.Itoa(t.Val)
21+
if t.Left != nil {
22+
ans += "(" + tree2str(t.Left) + ")"
23+
} else if t.Right != nil {
24+
ans += "()"
25+
}
26+
if t.Right != nil {
27+
ans += "(" + tree2str(t.Right) + ")"
28+
}
29+
}
30+
return ans
1531
}

‎problems/construct-string-from-binary-tree/construct_string_from_binary_tree_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@ func TestTree2str(t *testing.T) {
1515
tests := [...]caseType{
1616
{
1717
input: []int{1, 2, 3, 4},
18-
expected: "",
18+
expected: "1(2(4))(3)",
1919
},
2020
{
2121
input: []int{1, 2, 3, NULL, 4},
22-
expected: "",
22+
expected: "1(2()(4))(3)",
2323
},
2424
}
2525
for _, tc := range tests {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /