Data Structure and Algorithm Count Complete Tree Nodes 222. 完全二叉树的节点个数 分析 递归终止条件:如果当前节点为空,则返回 0,表示没有节点 递归步骤:对当前节点,递归计算其左子树和右子树的节点个数,然后返回左右子树节点数的和加上当前节点本身 时间复杂度 时间复杂度 O(n) 空间复杂度 空间复杂度为 O(logn) C++代码 1 2 3 4 5 6 7 8 9 10 11 12 13 class Solution { public: int countNodes(TreeNode* root) { // 如果树为空,节点个数为 0 if (!root) return 0; // 递归计算左子树和右子树的节点个数,并加上当前节点 return countNodes(root->left) + countNodes(root->right) + 1; } };