263. Count total nodes in a complete BT

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.

Example 1:

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

Output : 6

Explanation :

Example 2:

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

Output : 9

Explanation :

Now Your Turn!

Pick the correct output for the given input

Input : [1, 2, 3]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

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

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
int countNodes(TreeNode* root) {
//your code goes here
}
};
Test Case

Input:

Root