class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
auto l=root->left,r=root->right;
int x=1,y=1;//记录左右两边层数
while(l) l=l->left,x++;
while(r) r=r->right,y++;
if(x==y) return (1<<x)-1;//如果是满二叉树,节点树可以直接计算
else return 1+countNodes(root->left)+countNodes(root->right);
}
};
LeetCode 222. 完全二叉树的节点个数
发布时间 2023-05-24 14:22:29作者: 穿过雾的阴霾