완전 이진 트리의 노드수를 구하는 문제
아래의 조건을 만족해야 한다.
Design an algorithm that runs in less than O(n) time complexity.
/**
* 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) {
if (root == NULL)
{
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
};