Count Nodes in Complete Binary Tree
Given a complete binary tree root
, return the number of nodes in the tree.
This should be done in O((logn)2).
Constraints
n ≤ 100,000
wheren
is the number of nodes inroot
https://binarysearch.com/problems/Count-Nodes-in-Complete-Binary-Tree
ExamplesPermalink
Example 1Permalink
Input
- root =
Output
- answer =
5
Example 2Permalink
Input
- root =
Output
- answer =
7
SolutionPermalink
/** | |
* class Tree { | |
* public: | |
* int val; | |
* Tree *left; | |
* Tree *right; | |
* }; | |
*/ | |
int solve(Tree *root) | |
{ | |
int nLeft = 0, nRight = 0; | |
Tree *left = root, *right = root; | |
for (Tree *node = root; node; node = node->left, nLeft++) | |
; | |
for (Tree *node = root; node; node = node->right, nRight++) | |
; | |
if (nLeft == nRight) | |
{ | |
return (1 << nLeft) - 1; | |
} | |
return 1 + solve(root->left) + solve(root->right); | |
} |
Leave a comment