LeetCode 222. 完全二叉树的节点个数

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);
    }
};
posted @ 2023-05-24 14:15  穿过雾的阴霾  阅读(12)  评论(0)    收藏  举报