[leetcode] 222. Count Complete Tree Nodes

Description

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

分析

题目的意思是:给定一个完全二叉树,求其结点的个数。

  • 完全二叉树有一个很好的性质,对任一结点,如果其右子树的最大层次为L,则其左子树的最大层次为L或L+l。那么我们可以根据这个规律,分别求出左右子树的高度。如果左右高度一致,则为满二叉树,直接算出结点数就行了;否则分别递归左右子树。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root){
            return 0;
        }
        int lh=leftHeight(root);
        int rh=rightHeight(root);
        if(lh==rh) return pow(2,lh)-1;
        return countNodes(root->left)+countNodes(root->right)+1;
    }
    int leftHeight(TreeNode* root){
        if(!root){
            return 0;
        }
        return leftHeight(root->left)+1;
    }
    int rightHeight(TreeNode* root){
        if(!root){
            return 0;
        }
        return rightHeight(root->right)+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: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        l_cnt = self.countNodes(root.left)
        r_cnt = self.countNodes(root.right)
        return l_cnt+r_cnt+1

参考文献

[LeetCode] Count Complete Tree Nodes 求完全二叉树的节点个数
完全二叉树

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值