LeetCode Count Complete Tree Nodes

本文介绍了一种高效计算完全二叉树节点数量的方法。通过对比左右子树的高度判断是否为满二叉树,并利用位操作实现快速计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

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 2hnodes inclusive at the last level h.

题意:

求一棵完全二叉树的节点个数。

题解:

一开始,我用层次遍历来做,直接超时。然后考虑采用递归,就是分别对左右子树进行递归计算,最后就是左右子树的个数+1(root)。但是这里又有一个小技巧,就是首先先求左右子树的高度,如果这两个高度一样,那么就是满二叉树,那么我们就可以直接根据满二叉树的定义来求树的所有节点,node = 2 ^ h -1个节点。但是如果直接用java的Math.pow(double a,double b),那么就会超时,所以在求2的n次幂的时候,考虑用<<左移运算符。



Code:

public static int countNodes(TreeNode root)
	{
		if(root == null)
			return 0;
		TreeNode lt = root;
		TreeNode rt = root;
		int leftdepth = 0;
		int rightdepth = 0;
		while(lt != null)
		{
			leftdepth++;
			lt = lt.left;
		}
		while(rt != null)
		{
			rightdepth++;
			rt = rt.right;
		}
		if(leftdepth == rightdepth)
			return (1<<leftdepth) - 1;
		else 
			return countNodes(root.left) + countNodes(root.right) + 1;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值