-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathleetcode0102.go
46 lines (39 loc) · 864 Bytes
/
leetcode0102.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
LeetCode 102: https://leetcode.com/problems/binary-tree-level-order-traversal/
*/
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func levelOrder(root *TreeNode) [][]int {
result := make([][]int, 0)
if root == nil {
return result
}
queue1, queue2 := make([]*TreeNode, 0), make([]*TreeNode, 0)
level := make([]int, 0)
queue1 = append(queue1, root)
for len(queue1) > 0 {
node := queue1[0]
queue1 = queue1[1:]
level = append(level, node.Val)
if node.Left != nil {
queue2 = append(queue2, node.Left)
}
if node.Right != nil {
queue2 = append(queue2, node.Right)
}
if len(queue1) == 0 {
queue1 = queue2
queue2 = make([]*TreeNode, 0)
result = append(result, level)
level = make([]int, 0)
}
}
return result
}