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
// @Title: 二叉树的锯齿形层次遍历 (Binary Tree Zigzag Level Order Traversal)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 0 ms
// @Memory: 2.8 MB
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

 /*
func zigzagLevelOrder(root *TreeNode) [][]int {
	res := [][]int{}

	var dfs func(*TreeNode, int)
	dfs = func(root *TreeNode, level int) {
		if root == nil {
			return
		}
		// 出现新的level
		if level == len(res) {
			res = append(res, []int{})
		}
		// level的奇偶不同, append就会不同
		if level%2 >= 0 {
			res[level] = append(res[level], root.Val)
		} else {
			tmp := make([]int, len(res[level])+1)
			tmp[0] = root.Val
			copy(tmp[1:], res[level])
			res[level] = tmp
		}

		dfs(root.Left, level+1)
		dfs(root.Right, level+1)
	}

	dfs(root, 0)

	return res
}
*/
func zigzagLevelOrder(root *TreeNode) [][]int {
	res := [][]int{}

	var dfs func(*TreeNode, int)
	dfs = func(root *TreeNode, level int) {
		if root == nil {
			return
		}

		if level >= len(res) {
			res = append(res, []int{})
		}

		if level%2 == 0 {
			res[level] = append(res[level], root.Val)
		} else {
			tmp := make([]int, len(res[level])+1)
			tmp[0] = root.Val
			copy(tmp[1:], res[level])
			res[level] = tmp
		}

		dfs(root.Left, level+1)
		dfs(root.Right, level+1)
	}

	dfs(root, 0)

	return res
}