222 count complet tree nodes

完全树和满树的区别就在于最下面一层的叶子节点,完全树不是满的

当左右子树高度相同的时候,说明左子树是满树,所有节点就是1<<l + root->right 完全数的节点
当左小于右子树高度的时候,说明右子树是满树,所有节点就是1<<r + root->left 完全数的节点

int depth(struct TreeNode *root)
{
    #if 0
    if(root == NULL)
        return 0;

    int l = depth(root->left);
    int r = depth(root->right);

    return (l>r?l:r)+1;
    #else
    int h = 0;
    while(root){
        root = root->left;
        h++;
    }

    return h;
    #endif

}
int countNodes(struct TreeNode* root) {
    if(root == NULL)
        return 0;
    int l = depth(root->left);
    int r = depth(root->right);

    if(l == r)
        return (1<<l) + countNodes(root->right);
    else
        return (1<<r) + countNodes(root->left);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容