题目:
代码(首刷自解 2024年1月30日):
class Solution {
public:
int countNodes(TreeNode* root) {
int res = 0;
if (root == nullptr) return res;
queue<TreeNode*> deque;
TreeNode* cur = root;
deque.push(cur);
int size = 0;
while (!deque.empty()) {
size = deque.size();
while (size--) {
TreeNode* node = deque.front();
deque.pop();
res++;
if (node->left) deque.push(node->left);
if (node->right) deque.push(node->right);
}
}
return res;
}
};
代码 (首刷看解析 根据完全二叉树性质迭代)
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftDepth = 0;
int rightDepth = 0;
while (left) {
left = left->left;
leftDepth++;
}
while (right) {
right = right->right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};