038_二叉树的层序遍历

知识点:BFS(广度优先搜索)

LeetCode第一百零二题:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/submissions/

语言:GoLang

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) [][]int {
    result := [][]int{}

    if root == nil {
        return result
    }

    q := []*TreeNode{root}
    for len(q) > 0 {
        s := len(q)
        seqs := []int{}
        for i := 0; i < s; i++ {
            c := q[0]
            q = q[1:]

            seqs = append(seqs, c.Val)

            if c.Left != nil {
                q = append(q, c.Left)
            }
            if c.Right != nil {
                q = append(q, c.Right)
            }
        }
        result = append(result, seqs)
    }

    return result
}
posted @ 2020-03-27 19:47  Cenyol  阅读(91)  评论(0)    收藏  举报