nowcoder 完全二叉树计数

本文介绍了一种利用二分查找在O(logN)时间复杂度内求解完全二叉树节点数量的方法。通过计算根节点最左节点的深度,根据左右子树的深度关系递归计算节点数。

题目

给定一棵完全二叉树的根节点root,返回这棵树的节点个数。如果完全二叉树的节点数为N,请实现时间复杂度低于O(N)的解法。
给定树的根结点root,请返回树的大小。

思路

二分查找。统计根节点最左节点的深度。当左边深度和右边深度相同时,说明左边是完全二叉树,递归遍历右边,否则右边是完全二叉树,递归遍历左边。

代码

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class CountNodes:
    def getDepth(self, root):
        count = 0
        while root:
            count += 1
            root = root.left
        return count
    def count(self, root):
        # write code here
        if not root:
            return 0
        res = 0
        left_depth = 0; right_depth = 0
        left_depth = self.getDepth(root.left)
        right_depth = self.getDepth(root.right)
        if left_depth == right_depth:
            return 2 ** left_depth + self.count(root.right)
        else:
            return 2 ** right_depth + self.count(root.left)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值