[各种面试题] 完全二叉树节点个数的统计

本文介绍了一种利用完全二叉树特性优化节点计数的算法,通过比较左右子树深度,避免了传统O(n)遍历,显著提高了统计效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一棵完全二叉树(查看定义)的根结点,统计该树的结点总数。

树结点类型名为TreeNode,您没必要知道该类型的定义,请使用下面的方法得到某个结点的左,右儿子结点,以及判断某结点是否为NULL。

提示:使用 O(n) 的递归算法统计二叉树的结点数是一种显而易见的方法,此题中请利用 完全二叉树 的性质,想出效率更高的算法。


//使用getLeftChildNode(TreeNode)获得左儿子结点
//使用getRightChildNode(TreeNode)获得右儿子结点
//使用isNullNode(TreeNode)判断结点是否为空
int getDepth(TreeNode root)
{
    int depth=0;
    while(!isNullNode(root))
    {
        root=getLeftChildNode(root);
        depth++;
    }
    return depth;
}
int count_complete_binary_tree_nodes(TreeNode root) {
    if (isNullNode(root) )
        return 0;
    int lDepth=getDepth(getLeftChildNode(root));
    int rDepth=getDepth(getRightChildNode(root));
    if ( lDepth==rDepth )
        return (1<<lDepth)+count_complete_binary_tree_nodes(getRightChildNode(root));
    else
        return (1<<rDepth)+count_complete_binary_tree_nodes(getLeftChildNode(root));
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值