Skip to main content

222. Count Complete Tree Nodes

  • Recursion
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root)
{
int cnt = 0;
if (!root) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
  • T: O(n)O(n)
  • S: O(n)O(n)

2

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root)
{
int leftHeight = 0, rightHeight = 0;

TreeNode* leftNode = root;
TreeNode* rightNode = root;

while (leftNode)
{
++leftHeight;
leftNode = leftNode->left;
}

while (rightNode) {
++rightHeight;
rightNode = rightNode->right;
}

if (leftHeight == rightHeight)
{
return pow(2, leftHeight) - 1;
}

return countNodes(root->left) + countNodes(root->right) + 1;
}
};
  • T: O(lognlogn)O(\log n \cdot \log n)
  • S: O(n)O(n)