SA
Skip to main content

0104 Maximum Depth of Binary Tree

Solved at: 2023-01-29

Question

Maximum Depth of Binary Tree - LeetCode

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.

Solution

class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
guard root != nil else {return 0}
return max(maxDepth(root!.right), maxDepth(root!.left)) + 1
}
}

Results

  • Runtime 26 ms Beats 73.36%
  • Memory 14.7 MB Beats 58.61%

Complexity Analysis

  • Time: O(N)O(N)
  • Space: O(N)O(N)

Takeaways

We can also use BFS to traverse the tree