Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Max Depth

Treeseasy

A binary tree node is `{ val, left, right }` with `null` for empty. Implement `treeDepth(root)` returning the maximum depth (an empty tree has depth 0).

Sample tests

Input: treeDepth({"val":1,"left":{"val":2,"left":null,"right":null},"right":{"val":3,"left":null,"right":null}})
Output: 2
Input: treeDepth(null)
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Forgetting the null base case causes a crash.

Learning resources

  • Wikipedia: Binary tree
Approach & explanation (try first)

Recursion takes one plus the maximum depth of the two subtrees. O(n) over all nodes.

Loading...
⌘/Ctrl + Enter

Run your code to see results.