Created
December 15, 2022 23:35
-
-
Save abdulrahmanAlotaibi/fc65a92c532a84040406fe150de893e0 to your computer and use it in GitHub Desktop.
Trees : Maximum Depth of Binary Tree
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 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