leetcode-103 二叉树的锯齿形层次遍历

103. 二叉树的锯齿形层次遍历

难度: 中等




递归写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func zigzagLevelOrder(root *TreeNode) [][]int {
var res [][]int
search(root, 0, &res)
return res
}

func search(root *TreeNode, depth int, res *[][]int) {
if root == nil {
return
}
for len(*res) < depth+1 {
*res = append(*res, []int{})
}
if depth%2 == 0 {
(*res)[depth] = append((*res)[depth], root.Val)
} else {
(*res)[depth] = append([]int{root.Val}, (*res)[depth]...)
}
search(root.Left, depth+1, res)
search(root.Right, depth+1, res)
}

文章目录