Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Count Nodes

Treeseasy

Implement `treeCount(root)` returning the number of nodes.

Sample tests

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

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Counting null nodes as 1.

Learning resources

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

Each node counts one plus its subtree counts. O(n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.