Leetcode-222.完全二叉树的节点个数

题目

给出一个完全二叉树,求出该树的节点个数。

解法

  1. 最简单基础的方法,直接统计
# 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 is None:
            return 0
        return 1+self.countNodes(root.left)+self.countNodes(root.right)
  1. 利用完全二叉树的特点
    解法来源:https://leetcode-cn.com/problems/count-complete-tree-nodes/solution/chang-gui-jie-fa-he-ji-bai-100de-javajie-fa-by-xia/
class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        Node = 0
        if root is None:
            return 0
        # 统计左右子树的层数
        left = self.countLevel(root.left)
        right = self.countLevel(root.right)
        # 当左右层数相等,左子树为完全二叉树, 计算左子树的层数, 进一步统计右子树的结点数
        if left == right:
            Node += pow(2, left) + self.countNodes(root.right)
        # 当左右层数不相等, 右子树为完全二叉树, 计算右子树的层数, 进一步统计左子树结点数
        else:
            Node += pow(2, right) + self.countNodes(root.left)
        return Node 
    # 非递归,速度更快,更合理
    def countLevel(self, root):
        Level = 0
        while root is not None:
            Level += 1
            root = root.left
        return Level
    
    # 递归统计方法:其实没必要用递归
    def countLevel(self, root):
        if root is None: 
            return 0
        else:
            return max([self.countLevel(root.left), self.countLevel(root.right)])+1

在python里面,如果用了太多递归,第二种方法的耗时会比第一种还长。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值