问题描述:
给你二叉树的根节点root,返回其节点值的层序遍历,即逐层地,从左到右访问所有节点
示例:
输入: root = [3, 9, 20, null, null, 15, 7]
输出:[[3], [9, 20], [15, 7]]
package main import ( "fmt" ) type queue []*treeNode func(q *queue) push(v *treeNode) { *q = append(*q, v) } func(q *queue) pop() *treeNode { tmp := *q if len(tmp) == 0 { return nil } val := tmp[0] *q = tmp[1:] return val } func(q *queue) len() int { v := *q return len(v) } type treeNode struct { value int left *treeNode right *treeNode } func arrToTree(arr []int) *treeNode { length := len(arr) q := make(queue, 0) j := 0 root := &treeNode{ value: arr[0], } q.push(root) var tree *treeNode for i := 1; i < length; i++ { if j == 0 { tree = q.pop() tree.left = &treeNode{ value: arr[i], } q.push(tree.left) } else { tree.right = &treeNode{ value: arr[i], } q.push(tree.right) } j++ j = j % 2 } return root } func nodeAtLevel(tree *treeNode, level int, arr map[int][]int) { if tree == nil { return } if _, ok := arr[level]; !ok { arr[level] = []int{} } arr[level] = append(arr[level], tree.value) nodeAtLevel(tree.left, level + 1, arr) nodeAtLevel(tree.right, level + 1, arr) } func main() { // 默认-1为null tree := arrToTree([]int{3, 9, 20, -1, -1, 15, 7}) arr := map[int][]int{} nodeAtLevel(tree, 0, arr) fmt.Println("arr", arr) }