Skip to content

Commit dfdeaf3

Browse files
committed
Add verify-preorder-serialization-of-a-binary-tree
1 parent d4afe35 commit dfdeaf3

File tree

4 files changed

+64
-2
lines changed

4 files changed

+64
-2
lines changed

algorithms/binarysearch/69.mySqrt.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package binarysearch
22

3-
import _ "fmt"
4-
53
func mySqrt(x int) int {
64
left, right := 0, x
75
for left < right {

algorithms/linkedList/19.removeNthFromEnd_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ type (
1919
}
2020
)
2121

22+
// go test -v base.go 19.*
2223
func build_removeNthFromEnd_case() []entry19 {
2324
cases := []entry19{
2425
{
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package tree
2+
3+
import "strings"
4+
5+
func isValidSerialization(preorder string) bool {
6+
var leaves, node int
7+
pres := strings.Split(preorder, ",")
8+
for i, s := range pres {
9+
if s == "#" {
10+
leaves++
11+
} else {
12+
node++
13+
}
14+
if leaves > node+1 {
15+
return false
16+
}
17+
if leaves == node+1 && i < len(pres)-1 {
18+
return false
19+
}
20+
}
21+
22+
if leaves == node+1 {
23+
return true
24+
}
25+
return false
26+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package tree
2+
3+
import (
4+
"testing"
5+
6+
"Leetcode/algorithms/kit"
7+
)
8+
9+
// run: go test -v 331.*
10+
func Test_isValidSerialization(t *testing.T) {
11+
cases := []kit.CaseEntry{
12+
{
13+
Name: "x1",
14+
Input: "9,3,4,#,#,1,#,#,2,#,6,#,#",
15+
Expected: true,
16+
},
17+
{
18+
Name: "x2",
19+
Input: "1,#",
20+
Expected: false,
21+
},
22+
{
23+
Name: "x3",
24+
Input: "9,#,#,1",
25+
Expected: false,
26+
},
27+
// more test case
28+
}
29+
30+
for _, tt := range cases {
31+
t.Run(tt.Name, func(t *testing.T) {
32+
if output := isValidSerialization(tt.Input.(string)); output != tt.Expected.(bool) {
33+
t.Errorf("isValidSerialization(%s)=%t, expected=%t", tt.Input, output, tt.Expected.(bool))
34+
}
35+
})
36+
}
37+
}

0 commit comments

Comments
 (0)