美文网首页
二叉树的层序遍历

二叉树的层序遍历

作者: 7赢月 | 来源:发表于2020-05-13 17:50 被阅读0次

题目描述

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
}

思路

简单的层序遍历,增加难度的分层逻辑,这里使用了两个标识进行了层次的判断!

相关文章

网友评论

      本文标题:二叉树的层序遍历

      本文链接:https://www.haomeiwen.com/subject/nilonhtx.html