MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / levelOrder

Function levelOrder

binary_tree_level_order_traversal_102/solution.go:9–42  ·  view source on GitHub ↗

Slight variation of first correct solution below, which doesn't keep counters for the number of elements in a level. It just uses the current, constant size of the queue (before anything new is added to it).

(root *TreeNode)

Source from the content-addressed store, hash-verified

7// level. It just uses the current, constant size of the queue
8// (before anything new is added to it).
9func levelOrder(root *TreeNode) [][]int {
10 levels := make([][]int, 0)
11 if root == nil {
12 return levels
13 }
14
15 q := []*TreeNode{root}
16 for len(q) > 0 {
17 // dequeue and create level for the length
18 // of the currently enqueued level
19 level := make([]int, 0)
20 levelLen := len(q)
21 for i := 0; i < levelLen; i++ {
22 // add nodes value to the level
23 n := q[0]
24 level = append(level, n.Val)
25
26 if n.Left != nil {
27 q = append(q, n.Left)
28 }
29
30 if n.Right != nil {
31 q = append(q, n.Right)
32 }
33
34 // dequeue the node
35 q = q[1:]
36 }
37
38 levels = append(levels, level)
39 }
40
41 return levels
42}
43
44// Note: study again.
45func levelOrder0(root *TreeNode) [][]int {

Callers 1

Test_levelOrderFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_levelOrderFunction · 0.68