-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary-tree-zigzag-level-order-traversal.go
62 lines (44 loc) · 1.4 KB
/
binary-tree-zigzag-level-order-traversal.go
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
package algorithms
import "github.com/goldennovember/leetcode-go/gods"
type TreeNode = gods.TreeNode
func zigzagLevelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
var result [][]int
// Use a queue to store the nodes in the same level
var queue []*TreeNode
// Add the root to the queue
queue = append(queue, root)
level := 0
for len(queue) > 0 {
// currenLevelVal stores the values of the nodes in the current level
var currentLevelVal []int
// nextLevel stores the nodes in the next level
var nextLevel []*TreeNode
// Iterate through the nodes in the current level
for _, node := range queue {
// Add the value of the node to the currentLevelVal
currentLevelVal = append(currentLevelVal, node.Val)
// Add the left and right nodes (next level) to the nextLevel variable
if node.Left != nil {
nextLevel = append(nextLevel, node.Left)
}
if node.Right != nil {
nextLevel = append(nextLevel, node.Right)
}
}
if level%2 == 1 {
// Reverse the values of the nodes in the current level
for i, j := 0, len(currentLevelVal)-1; i < j; i, j = i+1, j-1 {
currentLevelVal[i], currentLevelVal[j] = currentLevelVal[j], currentLevelVal[i]
}
}
level++
// Add the values of the nodes in the current level to the result
result = append(result, currentLevelVal)
// Update the queue to the next level
queue = nextLevel
}
return result
}