18. Maximum Depth in BT

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

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

Example 1:

Input : root = [1, 2, 3, null, null, null , 6]

Output : 3

Explanation : The path from root node 1 to node with value 6 has maximum depth with 3 nodes along path.

Example 2:

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

Output : 3

Explanation : The path from root node 3 to node with value 15 has maximum depth with 3 nodes along path.

There exists other paths to reach the solution.

Now Your Turn!

Pick the correct output for the given input

Input : root = [5, 1, 2, 8, null, null, 5, null, 4, null, null, 7]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • 0 <= Node.val <= 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
int maxDepth(TreeNode* root) {
//your code goes here
}
};
Test Case

Input:

Root