222. Count Complete Tree Nodes
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6int 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;
}Last updated