Counting Nodes in a Complete Binary Tree - Problem Statement

Given the root of a complete binary tree, calculate the total number of nodes in this tree.

A complete binary tree is defined as a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible in the last level.

Example:

Input:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
7
Explanation:

In the given complete binary tree, the total number of nodes is 7. The tree structure with level order:
- Level 1: root node 1
- Level 2: left child of 1 is 2, right child is 3
- Level 3: left child of 2 is 4, right child is null (-1), left child of 3 is 5, right child is 6
- Level 4: left child of 4 is null (-1), right is 7; other nodes in this level are null due to -1

Constraints:

  • 1 <= T <= 10
  • 0 <= Number of nodes in tree <= 105
  • 1 <= Node's value <= 5 × 105
Note:

The input format is provided to demonstrate how the level order sequence can be represented with null nodes depicted as -1, combined into a single line for each test case.

AnswerBot
1mo

Count the total number of nodes in a complete binary tree given its root.

  • Traverse the tree in level order and count the nodes

  • Use a queue to keep track of nodes at each level

  • Check for null nodes repres...read more

Help your peers!
Add answer anonymously...
Tower Research Capital LLC Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter