Skip to content

Instantly share code, notes, and snippets.

@abdulrahmanAlotaibi
Created December 15, 2022 23:35
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 abdulrahmanAlotaibi/fc65a92c532a84040406fe150de893e0 to your computer and use it in GitHub Desktop.
Save abdulrahmanAlotaibi/fc65a92c532a84040406fe150de893e0 to your computer and use it in GitHub Desktop.
Trees : Maximum Depth of Binary Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type t struct {
n *TreeNode
d int
}
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
stack := []*t{
&t{
n : root,
d : 1,
},
}
depth := 0
for len(stack) > 0 {
s := stack[len(stack)-1]
stack = stack[:len(stack)-1]
n := s.n
nDepth := s.d
if nDepth > depth {
depth = nDepth
}
if n.Right != nil {
stack = append(stack, &t{
n : n.Right,
d:nDepth+1,
})
}
if n.Left != nil {
stack = append(stack, &t{
n : n.Left,
d : nDepth+1,
})
}
}
return depth
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment