Skip to content

Commit 12e2ab5

Browse files
author
legolas.zhan
committed
117. Populating Next Right Pointers in Each Node II
1 parent 9e9cb0e commit 12e2ab5

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed

leetcode/others/connect.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package lothers
2+
3+
type Node struct {
4+
Val int
5+
Left *Node
6+
Right *Node
7+
Next *Node
8+
}
9+
10+
func connect(root *Node) *Node {
11+
if root == nil {
12+
return nil
13+
}
14+
15+
queue := []*Node{root}
16+
for len(queue) > 0 {
17+
levelSize := len(queue)
18+
for i := 0; i < levelSize; i++ {
19+
node := queue[i]
20+
if i < levelSize-1 {
21+
node.Next = queue[i+1]
22+
}
23+
24+
if node.Left != nil {
25+
queue = append(queue, node.Left)
26+
}
27+
if node.Right != nil {
28+
queue = append(queue, node.Right)
29+
}
30+
}
31+
queue = queue[levelSize:]
32+
}
33+
return root
34+
}

leetcode/others/connect_test.go

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package lothers
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestConnect(t *testing.T) {
10+
tests := []struct {
11+
name string
12+
root *Node
13+
expected []interface{}
14+
}{
15+
{
16+
name: "Example 1",
17+
root: &Node{
18+
Val: 1,
19+
Left: &Node{
20+
Val: 2,
21+
Left: &Node{
22+
Val: 4,
23+
},
24+
Right: &Node{
25+
Val: 5,
26+
},
27+
},
28+
Right: &Node{
29+
Val: 3,
30+
Right: &Node{
31+
Val: 7,
32+
},
33+
},
34+
},
35+
expected: []interface{}{1, "#", 2, 3, "#", 4, 5, 7, "#"},
36+
},
37+
{
38+
name: "Example 2",
39+
root: nil,
40+
expected: []interface{}{},
41+
},
42+
}
43+
44+
for _, tt := range tests {
45+
t.Run(tt.name, func(t *testing.T) {
46+
root := connect(tt.root)
47+
48+
// Serialize the tree and check the result
49+
result := serializeTree(root)
50+
assert.Equal(t, tt.expected, result)
51+
})
52+
}
53+
}
54+
55+
func serializeTree(root *Node) []interface{} {
56+
if root == nil {
57+
return []interface{}{}
58+
}
59+
queue := []*Node{root}
60+
var result []interface{}
61+
for len(queue) > 0 {
62+
levelSize := len(queue)
63+
for i := 0; i < levelSize; i++ {
64+
node := queue[i]
65+
result = append(result, node.Val)
66+
if i == levelSize-1 {
67+
result = append(result, "#")
68+
}
69+
if node.Left != nil {
70+
queue = append(queue, node.Left)
71+
}
72+
if node.Right != nil {
73+
queue = append(queue, node.Right)
74+
}
75+
}
76+
queue = queue[levelSize:]
77+
}
78+
return result
79+
}

0 commit comments

Comments
 (0)