Created
April 15, 2022 15:19
-
-
Save MorrisLaw/435c612b6ae431ac6dff92e4cccbce22 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] | |
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.