⌘K
Flycodx

Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

EasyTrees25% accepted

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

7 3 9 20 -1 -1 15 7

Output

3
  • •0 ≤ n ≤ 10^4 (n=0 means empty tree, depth = 0)
solution.py
Loading editor...
Test 1
Test 2
Test 3

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
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3