(LeetCode) Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

  • Explore : Interview > Top Interveiw Questions > Easy Collection
  • 분류 : Trees
  • 난이도 : Easy

Problem

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

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

Example 2

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

Example 3

1
2
Input: root = []
Output: 0

Example 4

1
2
Input: root = [0]
Output: 1

Constraints

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

Solution

Exapnder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun maxDepth(root: TreeNode?): Int {
return if (root == null) {
0
} else {
Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
}
}
}

Point of Thinking

  • DFS 문제이므로 재귀함수로 처리하면 간단하게 해결할 수 있다.