【leetcode】-222. Count Complete Tree Nodes计算完全二叉树结点数

题目

Given a complete binary tree, count the number of nodes.

Note:

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example:

Input:

  1
 / \
2   3
/ \  /
4  5 6

Output: 6

树的递归

二叉树的遍历,先处理根结点后递归子树。

python 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        return 1+self.countNodes(root.left)+self.countNodes(root.right)

完全二叉树递归

利用完全二叉树的性质,完全二叉树从满二叉树的右边开始缺少结点。满二叉树一定是完全二叉树,完全二叉树不一定是满二叉树。
如果是满二叉树,那么结点数就与树的高度相关:2^h-1。
如果完全二叉树缺少的最后一个结点在右边,那么对于根的左子树是满二叉树,对于其右子树是完全二叉树,且左右子树的高度相等;如果完全二叉树缺少的最后一个结点在左边,那么左子树的高度等于右子树的高度+1,且对于根的左子树是完全二叉树,对于其右子树是满二叉树。

python 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        lHeight = self.getHeight(root.left)
        rHeight = self.getHeight(root.right)
        if lHeight == rHeight:
            return (1<<lHeight) + self.countNodes(root.right)
        if lHeight != rHeight:
            return self.countNodes(root.left) + (1<<rHeight)
        
    def getHeight(self,root):
        if not root:
            return 0
        return self.getHeight(root.left)+1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值