Leetcode - Excel Sheet Column Number
Leetcode - Flood Fill

Leetcode - N-ary Tree Level Order Traversal

violet posted @ May 10, 2020 06:58:24 AM in 算法 with tags Algorithm Golang tree , 353 阅读

https://leetcode.com/problems/n-ary-tree-level-order-traversal/

Given an n-ary tree, return the level order traversal of its nodes' values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

 

Example 1:

Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]

 

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func levelOrder(root *Node) [][]int {
    result := [][]int{}
    if root == nil {
        return result
    }
    queue := []*Node{root}
    for len(queue) != 0 {
        size := len(queue)
        tmp := []int{}
        for i := 0; i < size; i++ {
            node := queue[i]
            tmp = append(tmp, node.Val)
            for _, c := range node.Children {
                queue = append(queue, c)
            }
        }
        queue = queue[size:]
        result = append(result, tmp)
    }
    
    return result
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter