美文网首页
222 count complet tree nodes

222 count complet tree nodes

作者: larrymusk | 来源:发表于2017-11-20 13:16 被阅读0次

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

当左右子树高度相同的时候,说明左子树是满树,所有节点就是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);
}

相关文章

网友评论

      本文标题:222 count complet tree nodes

      本文链接:https://www.haomeiwen.com/subject/itlvvxtx.html