-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathsolution.go
54 lines (49 loc) · 985 Bytes
/
solution.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
package leetcode
/*
* @lc app=leetcode.cn id=103 lang=golang
*
* [103] 二叉树的锯齿形层次遍历
*/
// @lc code=start
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func zigzagLevelOrder(root *TreeNode) [][]int {
res := [][]int{}
if root == nil {
return res
}
queue := []*TreeNode{root}
for level := 0; len(queue) > 0; level++ {
l := len(queue)
list := []int{}
for i := 0; i < l; i++ {
node := queue[i]
if level%2 == 0 {
list = append(list, node.Val)
} else {
list = append([]int{node.Val}, list...)
}
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
queue = queue[l:]
res = append(res, list)
}
return res
}
// @lc code=end