Alan Zhan Blog

Live for nothing, or die for something

104. Maximum Depth of Binary Tree

https://leetcode.com/problems/maximum-depth-of-binary-tree/

Easy


Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -100 <= Node.val <= 100

Problem

Find the deepest node in the tree — what is its depth?

Approach

This problem is similar to 226 Invert Binary Tree, and we’ll also use recursion, but with a different approach.

Treat each node as a root node, declare a depth variable, increment by 1 going down each level and decrement by 1 going up. Traverse all nodes, updating the answer whenever the depth increases. Finally, return the answer.

  1. Declare global depth and result variables.
  2. Start recursive traversal — increment the depth variable by 1 when going deeper, decrement by 1 when going back up.
  3. Treat left and right children as roots, continuing to recursively call the calculateDepth method.
  4. Whenever depth exceeds the current result, update the result to the current depth.

Source Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
var depth int
var ans int
func maxDepth(root *TreeNode) int {
    depth = 1
    ans = 0
    calculateDepth(root)
    return ans
}

func calculateDepth(root *TreeNode) {
    if root == nil {
        return
    }

    if ans < depth {
        ans = depth
    }

    depth++
    calculateDepth(root.Left)
    calculateDepth(root.Right)
    depth--
}

Closing

Do you have a better or simpler solution?

Feel free to leave a comment on my blog. Your feedback motivates me to keep writing. Thank you for reading, and let’s grow together to become better versions of ourselves.