Java for LeetCode 222 Count Complete Tree Nodes
2024-09-25 19:59:26
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 2h nodes inclusive at the last level h.
解题思路:
计算完全二叉树节点,直接递归会TLE,一个不错的思路是判断是否为满二叉树,然后进行递归,JAVA实现如下:
public int countNodes(TreeNode root) {
if(root==null)
return 0;
int leftHeight=1,rightHeight=1;
TreeNode temp=root.left;
while(temp!=null){
temp=temp.left;
leftHeight++;
}
temp=root.right;
while(temp!=null){
temp=temp.right;
rightHeight++;
}
if(leftHeight==rightHeight)
return (1<<leftHeight)-1;
return countNodes(root.left)+countNodes(root.right)+1;
}
最新文章
- 安装ganglia
- 微信小程序之登录态维护(十一)
- Blackfin DSP(四):BF533 EBIU之SDRAM
- java获取点击微信自定义菜单的用户openid
- 我发现:在StackOverflow上拯救歪果仁十分有意思!
- 浏览器获取ip地址
- 使用CSS3实现超炫的Loading(加载)动画效果
- VNC Server 配置
- jQuery 事件 方法
- 修真院java后端工程师学习课程--任务1(day four)
- 获取具有指定扩展数据的所有实体的Id,并存入Id数组中
- VScode查找替换常用正则表达式
- CodeForces 937D 936B	Sleepy Game 有向图判环,拆点,DFS
- Codeforces Round #309 (Div. 2) -D. Kyoya and Permutation
- Tomcat架构解析(四)-----Coyote、HTTP、AJP、HTTP2等协议
- MySQL &#183; 关系模型的基本术语
- 25-[jQuery]-事件
- 在Ubuntu 12.04 桌面上设置启动器(快捷方式)
- UTF-8中的BOM
- Http请求超时的一种处理方法