Created
April 15, 2022 14:11
-
-
Save MorrisLaw/df79072e87caef9842eab1c9b3a01845 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* type TreeNode struct { | |
* Val int | |
* Left *TreeNode | |
* Right *TreeNode | |
* } | |
*/ | |
type Queue struct { | |
nodes []*TreeNode | |
} | |
func (q *Queue) pop() *TreeNode { | |
node := q.nodes[len(q.nodes)-1] | |
if len(q.nodes) > 0 { | |
q.nodes = q.nodes[:len(q.nodes)-1] | |
} | |
return node | |
} | |
func (q *Queue) add(node *TreeNode) { | |
q.nodes = append([]*TreeNode{node}, q.nodes...) | |
} | |
func (q *Queue) size() int { | |
return len(q.nodes) | |
} | |
func NewQueue(root *TreeNode) *Queue { | |
return &Queue {[]*TreeNode{root}} | |
} | |
func levelOrder(root *TreeNode) [][]int { | |
if root == nil { | |
return nil | |
} | |
q := NewQueue(root) | |
var result [][]int | |
for len(q.nodes) != 0 { | |
size := q.size() | |
var currLvl []int | |
for i := 0; i < size; i++ { | |
curr := q.pop() | |
currLvl = append(currLvl, curr.Val) | |
if curr.Left != nil { | |
q.add(curr.Left) | |
} | |
if curr.Right != nil { | |
q.add(curr.Right) | |
} | |
} | |
result = append(result, currLvl) | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the first half of the file, it's mostly helper functions to make a queue like data structure. With
pop
taking nodes off of the end of a slice andadd
prepending nodes to a slice. Just like a queue would.The algorithm is as follows: