forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0102-binary-tree-level-order-traversal.go
42 lines (38 loc) · 1.03 KB
/
0102-binary-tree-level-order-traversal.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
funclevelOrder(root*TreeNode) [][]int {
// nil check
ifroot==nil {
returnnil
}
varresult [][]int
level:=0
q:=make([]*TreeNode,1)
q[0] =root
forlen(q) >0 {
curLen:=len(q)
//add elements to the queue per level
fori:=0; i<curLen; i++ {
//queue implementation : delete element from front(1st element of slice)
node:=q[0]
q=q[1:]
iflen(result) <=level {
//create new slice with first value of the level and append to result matrix
result=append(result,[]int{node.Val})
}else {
//add values to the slice created per level
result[level] =append(result[level],node.Val)
}
//queue implementation : add element at Back( after last element of slice by append)
//add left node at queue
ifnode.Left!=nil {
q=append(q,node.Left)
}
//add Right node at queue
ifnode.Right!=nil{
q=append(q,node.Right)
}
}
//increment the level after adding current elements to result
level++
}
returnresult
}