当前位置:网站首页>222. 完全二叉树的节点个数
222. 完全二叉树的节点个数
2022-07-27 02:19:00 【小卢要刷力扣题】
222. 完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-complete-tree-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路

完全二叉树的高度怎么求?一直往左看,看最深到第几层就是完全二叉树的高度
首先数一下一共有几层,然后找右数上的最左节点如果没有达到最大深度5层,现在只有4层说明
右树是满的,高度是3

因为我们永远有总层数,如果总层数10层,
如果当前节点在第5层,如果发现右树上的最左节点没到第10层,到第9层
说明右树是满的,高度是4
右树节点个数为24

如果总层数10层,右树上的最左节点到了第10层,说明左树是满的,高度是5
永远在找头节点右树上的最左
它如果到了最后一层,左边直接公式求出来了
它如果没到最后一层, 右边一个公式求出来,之后走左边递归。
永远都看右树最左决定你走左还是走右
代码
class Solution {
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
return bs(root,1,mostLestLevel(root,1));
}
public int bs(TreeNode root,int level,int h){
if(level==h){
return 1;
}
if(mostLestLevel(root.right,level+1)==h){
return (1<<(h-level))+bs(root.right,level+1,h);
}else{
return (1<<(h-level-1))+bs(root.left,level+1,h);
}
}
public int mostLestLevel(TreeNode node,int level){
while(node!=null){
level++;
node=node.left;
}
return level-1;
}
}
边栏推荐
- Mysql database related operations
- If the detailed explanation is generated according to the frame code
- 数据库概论 - MySQL的简单介绍
- 复盘:DFS与BFS的主要区别,在思想上的区别,代码实现上的区别
- Ring counting (Northern Polytechnic machine test questions) (day 83)
- Introduction to database - a brief introduction to MySQL
- Solution to Chinese garbled code in console header after idea connects to database to query data
- Quick sequencing and optimization
- Practical application of digital twins: smart city project construction solution
- Installation and use of anti-virus software ClamAV
猜你喜欢
随机推荐
Learning and understanding of four special data types of redis
Director of meta quest content ecology talks about the original intention of APP lab design
一种分布式深度学习编程新范式:Global Tensor
复盘:图像有哪些基本属性?关于图像的知识你知道哪些?图像的参数有哪些
Principle understanding and application of hash table and consistent hash
Implementation of API short message gateway based on golang
Common weak password Encyclopedia
Number of 0 at the end of factorial
How can you access the domestic server and overseas server quickly with one database?
Number of square arrays (day 81)
【无标题】JDBC连接数据库读超时
Kettle reads file split by line
The function and application of lpci-252 universal PCI interface can card
Meta Quest内容生态总监谈App Lab设计初衷
Daffodils (day 78)
DataX无法连接对应的数据库(windows下可以,linux下失败)
Source code analysis of openfeign
Two help points distribution brings to merchants
Connman introduction
Contour detection based on OpenCV (2)









