Count total nodes in a complete BT

Binary Trees FAQs Hard

Return the number of nodes in a binary tree given its root.


Every level in a complete binary tree possibly with the exception of the final one is fully filled, and every node in the final level is as far to the left as it can be. At the last level h, it can have 1 to 2h nodes inclusive.

Examples:

Input : root = [1, 2, 3, 4, 5, 6]

Output : 6

Explanation :

Input : root = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Output : 9

Explanation :

Input : [1, 2, 3]

Constraints

  • 1 <= Number of Node <= 5*104
  • -105 <= Node.val <= 105
  • The tree is guaranteed to be complete.

Hints

  • Perform a DFS (recursive) or BFS (iterative) traversal. Maintain a counter that increments for each node encountered. Base Case: If the root is null, return 0.
  • If a tree is complete, its height can be determined by following the leftmost path. A complete binary tree has at most 2^h - 1 nodes. The last level may not be completely full, meaning we need to count nodes in the last level.

Company Tags

Cerner Optum Freshworks Unity Technologies Philips Healthcare HCL Technologies Goldman Sachs Shopify Visa IBM Zoho Instacart Bloomberg Broadcom Pinterest Medtronic Rakuten eBay Johnson & Johnson Robinhood Reddit Rockstar Games HashiCorp Walmart Dropbox Google Microsoft Amazon Meta Apple Netflix Adobe