After other problems related to heights, this is an easy one. Find the maximum distance from the root to a leaf in a binary tree.
My first cut had an extra check for the null-left, null-right node, but I realized that the extra call with a nil pointer was faster than an extra conditional in the main path.
**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return 1 + max(maxDepth(root.Left), maxDepth(root.Right))
}
func max(a, b int) int {
if a >= b {
return a
}
return b
}
100% on speed, 26% on memory. Finished about as fast as I could type it.
Leave a Reply
You must be logged in to post a comment.