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);
    }
};
    有帮助的话可以点个赞,我会很开心的~
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号