-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpopulating_next_right_pointers_in_each_node.go
More file actions
80 lines (72 loc) · 1.33 KB
/
Copy pathpopulating_next_right_pointers_in_each_node.go
File metadata and controls
80 lines (72 loc) · 1.33 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package leetcode
// Definition for a Node.
type Node struct {
Val int
Left *Node
Right *Node
Next *Node
}
// Time complexity: O(n) where n is the number of nodes
// Space complexity: O(n)
// DFS
func connect(root *Node) *Node {
if root == nil {
return root
}
if root.Left != nil {
root.Left.Next = root.Right
if root.Next != nil {
root.Right.Next = root.Next.Left
}
}
connect(root.Left)
connect(root.Right)
return root
}
// Time complexity: O(n) where n is the number of nodes
// Space complexity: O(1)
// BFS
// Note: This is an optimized version for space
func connect2(root *Node) *Node {
head := root
for head != nil {
curr := head
for curr != nil {
if curr.Left != nil {
curr.Left.Next = curr.Right
if curr.Next != nil {
curr.Right.Next = curr.Next.Left
}
}
curr = curr.Next
}
head = head.Left
}
return root
}
// Time complexity: O(n) where n is the number of nodes
// Space complexity: O(n)
// BFS
func connect3(root *Node) *Node {
if root == nil {
return root
}
deq := []*Node{root}
for len(deq) > 0 {
n := len(deq)
for i := 0; i < n; i++ {
node := deq[0]
deq = deq[1:]
if i < n-1 {
node.Next = deq[0]
}
if node.Left != nil {
deq = append(deq, node.Left)
}
if node.Right != nil {
deq = append(deq, node.Right)
}
}
}
return root
}