[LeetCode]222. Count Complete Tree Nodes

本文介绍了一种计算完全二叉树中节点数量的方法。通过判断左右子树是否为满二叉树来递归计算节点总数。文章提供了一个Java实现示例。

https://leetcode.com/problems/count-complete-tree-nodes/

计算完全二叉树中的节点个数




完全二叉树当前结点的左右子树至少有一个是满二叉树

// 完全二叉树树的高度为根节点到最左子树的长度
public class Solution {
    public int countNodes(TreeNode root) {
        // height(root.right) == h - 1表明左子树为满二叉树,再加上root,总共为1 << h,
        // height(root.right) == h - 2表明右子树为满二叉树
        int h = height(root);
        // 位运算全部加括号!!!
        return h < 0 ? 0 : 
            height(root.right) == h - 1 ? (1 << h) + countNodes(root.right) : 
                (1 << (h - 1)) + countNodes(root.left);
    }
    private int height(TreeNode root) {
        if (root == null) {
            return -1;
        }
        return 1 + height(root.left);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值