题目描述
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
解
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return nil
}
var (
r [][]int
t []*TreeNode
l []int
c int
n int
)
t = append(t, root)
c++
for len(t) != 0 {
info := t[0]
t = t[1:] // 删除队尾
c--
l = append(l, info.Val)
if info.Left != nil {
n++
t = append(t, info.Left)
}
if info.Right != nil {
n++
t = append(t, info.Right)
}
if c == 0 {
c = n
n = 0
r = append(r, l)
l = []int{}
}
}
return r
}
思路
简单的层序遍历,增加难度的分层逻辑,这里使用了两个标识进行了层次的判断!
网友评论