222. Count Complete Tree Nodes [Medium] 二分查找

222. Count Complete Tree Nodes

17368230-6204cb28620f5a66.png
222. Count Complete Tree Nodes

最简单的就是遍历计数,但是没有用到Complete Tree的特性,先来个递归版本

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

再来一个深度优先的循环版本吧

class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        stack = []
        node = root
        res = 0
        while node or stack:
            while node:
                stack.append(node)
                node = node.left
                res += 1
            if stack != None:
                node = stack.pop()
                node = node.right
        return res

这道题的标签是二分查找,要用到Complete Tree的性质,如果是完全二叉树,知道深度就可以得到节点数,如果不是,递归求解

class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        left = self.countLeft(root)
        right = self.countRight(root)
        if left == right:
            return (1<<left) - 1
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)
        
    def countLeft(self, root):
        res = 0
        while root:
            root = root.left
            res += 1
        return res
    
    def countRight(self, root):
        res = 0
        while root:
            root = root.right
            res += 1
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值