222. Count Complete Tree Nodes
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
int countNodes(TreeNode* root) { // time: O(n^2); space: O(n)
int left_h = 0, right_h = 0;
TreeNode *left_ptr = root, *right_ptr = root;
while (left_ptr) {
++left_h;
left_ptr = left_ptr->left;
}
while (right_ptr) {
++right_h;
right_ptr = right_ptr->right;
}
if (left_h == right_h) return pow(2, left_h) - 1;
return countNodes(root->left) + countNodes(root->right) + 1;
}
int leftHeight(TreeNode* root) {
if (!root) return 0;
return 1 + leftHeight(root->left);
}
int rightHeight(TreeNode* root) {
if (!root) return 0;
return 1 + rightHeight(root->right);
}
int countNodes(TreeNode* root) { // time: O(n^2); space: O(n)
int left_h = leftHeight(root), right_h = rightHeight(root);
if (left_h == right_h) return pow(2, left_h) - 1;
return countNodes(root->left) + countNodes(root->right) + 1;
}
Last updated
Was this helpful?