Maximum Depth of Binary Tree
Maximum Depth of Binary Tree
Given a binary tree represented as a level-order (BFS) array, find and print its maximum depth. The maximum depth is the length of the longest path from the root node down to the farthest leaf node, counting the number of nodes along the path. A leaf node is a node with no children. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: level-order [3 9 20 -1 -1 15 7] → depth 3 (path: 3 → 20 → 15 or 3 → 20 → 7)
Input format — only if your code reads from stdin
Input format (stdin): - First line: integer n (number of values in the level-order array) - Second line: n space-separated integers, where -1 represents a null node Output: a single integer — the maximum depth.
Approach
Recursively compute depth: maxDepth(node) = 1 + max(maxDepth(left), maxDepth(right)), with base case maxDepth(null) = 0. Alternatively, use BFS and count levels — increment depth each time you process an entire level.
Input
Output
- •
0 ≤ n ≤ 10^4 (n=0 means empty tree, depth = 0)
More Trees problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards