Skip to content

Instantly share code, notes, and snippets.

@MorrisLaw
Created April 15, 2022 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MorrisLaw/435c612b6ae431ac6dff92e4cccbce22 to your computer and use it in GitHub Desktop.
Save MorrisLaw/435c612b6ae431ac6dff92e4cccbce22 to your computer and use it in GitHub Desktop.
/**
* 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]
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 maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
q := NewQueue(root)
var result [][]*TreeNode
for q.size() != 0 {
size := q.size()
var currLvl []*TreeNode
for i := 0; i < size; i++ {
currNode := q.pop()
currLvl = append(currLvl, currNode)
if currNode.Left != nil {
q.add(currNode.Left)
}
if currNode.Right != nil {
q.add(currNode.Right)
}
}
result = append(result, currLvl)
}
return len(result)
}
@MorrisLaw
Copy link
Author

Similar to the level order traversal, except I'm just returning the size of the resulting slice which represents the total number of levels that exist for this binary tree, a.k.a, the max depth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment