104. Maximum Depth of Binary Tree
Question:
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:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Input: root = [1,null,2]
Output: 2
Input: root = []
Output: 0
Input: root = [0]
Output: 1
Source code
Version 1
Idea:
Basically, I konw the search must be throughout all link of the whole tree, then if the left/right node of root are NULL, the depth is the deepest, so depth is start from 1 (depth + 1). But, I can't find out any regular action by using the recursion.
There is a quit clear demonstration as below[1]: It's very helpful and let me understand the recursion processing. So, let me explain the code:
(1) maxDepth(root->left)
: use recursion to find deepest depth of left node
(2) maxDepth(root->right
: use recursion to find deepest depth of right node
(3) max((1), (2))
: compare the deepest depth of both of left/right nodes, get the maximum value. Then, + 1
means adding this layer.
1 | /** |
Reference:
[1] https://algorithms.tutorialhorizon.com/find-the-maximum-depth-or-height-of-a-binary-tree/