当前位置:网站首页>Number of nodes of complete binary tree
Number of nodes of complete binary tree
2022-04-23 12:20:00 【skeet follower】
Welcome to you, Daily brush series
The number of nodes in a complete binary tree
The number of nodes in a complete binary tree
Let's use ordinary binary tree to solve this problem . Find the number of nodes of an ordinary binary tree , Nothing more than recursion or iteration .
Recursion is similar to what we said earlier The maximum depth of a binary tree similar , Iteration is the same as what we said earlier The maximum depth of a binary tree The code is very similar , Just change a little .
recursive
According to the recursive trilogy .
1. Determine the parameters and return values of recursive functions : The parameter is the root node of the incoming tree , Returns the number of nodes in the binary tree with this node as the root node , So the return value is int type .
int _countNodes(TreeNode* root)
2. Determine the single-layer loop logic : First find the number of nodes in its left subtree , Then find the number of nodes of the right subtree , Finally, take the sum and add one ( Add 1 Because the current intermediate node is included ) This is the number of nodes whose current node is the root node .
int leftnum=_countNodes(root->left); int rightnum=_countNodes(root->right); int treenum=leftnum+rightnum+1; return treenum;
3. Determine the closing conditions :
if(root==nullptr) { return 0; }
Code :
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr)
{
return 0;
}
int left=countNodes(root->left);
int right=countNodes(root->right);
return left+right+1;
}
};
iteration
The template of sequence traversal mentioned earlier , You can go and have a look , Here I'll go straight to the code
Code :
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr)
{
return 0;
}
queue<TreeNode*> q;
q.push(root);
int result=0;
while(!q.empty())
{
int size=q.size();
for(int i=0;i<size;i++)
{
TreeNode* node=q.front();
q.pop();
result++;
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
}
return result;
}
};
Let's take a look at the time complexity and space complexity of the above code :
recursive :
- Time complexity :O(n)
- Spatial complexity :O(log n)
iteration :
- Time complexity :O(n)
- Spatial complexity :O(n)
Can we use the characteristics of complete binary tree to optimize the time complexity ?
Optimize practices
Completely Binary trees are more special than ordinary binary trees , But it's not as special as a full binary tree , Calculate its total number of nodes , It can be said to be a combined version of ordinary binary tree and full , Look at the code first :
If it's a Ordinary Binary tree , Obviously, you just have to traverse one side down like this , Time complexity O(N):
int countNodes(TreeNode* root) {
return 1+countNodes(root->left)+countNode(root->right);
}
If it's a tree full Binary tree , The total number of nodes is exponentially related to the height of the tree :
int countNodes(TreeNode* root) {
int h = 0;
// Calculate the height of the tree
while (root != null) {
root = root.left;
h++;
}
// The total number of nodes is 2^h - 1
return (int)Math.pow(2, h) - 1;
}
Code :
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr)
{
return 0;
}
TreeNode* l=root;
TreeNode* r=root;
// Record the height of the left and right subtrees
int h1=0,h2=0;
while(l!=nullptr)
{
l=l->left;
h1++;
}
while(r!=nullptr)
{
r=r->right;
h2++;
}
// If the height of the left and right subtrees is the same , Is a full binary tree
if(h1==h2)
{
return (int)pow(2, h1) - 1;
}
// If the height is different, it is calculated according to the ordinary binary tree
return countNodes(root->left)+countNodes(root->right)+1;
}
};
- Time complexity :O(log n × log n)
- Spatial complexity :O(log n)
So ,「 Perfect binary tree 」 There are still reasons for this concept , It's not only suitable for arrays to implement binary heaps , And even the seemingly simple operation of calculating the total number of nodes has efficient algorithm implementation .
版权声明
本文为[skeet follower]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231217490052.html
边栏推荐
- 对称加密、证书加密
- Qt进程间通信
- QT draw text
- How to switch PHP version in Windows 2008 system
- SynchronousQueue 源码解析
- The database navigator uses the default MySQL connection prompt: the server time zone value 'Ö Ð¹ ú±ê ×¼ ʱ ¼ ä’ is unrecognized or repres
- Why is the premise of hash% length = = hash & (length-1) that length is the nth power of 2
- 电脑系统卡如何解决?
- QT redraw events and cuts
- Optimize connections using connection groups (IM 6)
猜你喜欢
How do traditional enterprises cope with digital transformation? These books give you the answer
Next. JS static data generation and server-side rendering
九十八、freemarker框架报错 s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request
远程桌面之终端服务器超出了最大允许连接数解决
QT draw text
软件测试基础DAY2-用例执行
欣旺达宣布电池产品涨价 此前获“蔚小理”投资超10亿
Idea code quality specification plug-in sonarlint
如果你是一个Golang面试官,你会问哪些问题?
QT one process runs another
随机推荐
STM32CubeProgrammer基础使用说明
Nativeformysql connects to MySQL 8 prompt: 1251 - client does not support authentication protocol
The fourth chapter is the enable and disable columns of IM enabled fill objects (Part III of im-4.3)
AI video cloud vs narrowband HD, who is the darling of the video era
欣旺达宣布电池产品涨价 此前获“蔚小理”投资超10亿
uni-app 原生APP-云打包集成极光推送(JG-JPUSH)详细教程
软银愿景基金进军Web3安全行业 领投CertiK 6000万美元新一轮投资
【unity笔记】L4Unity中的基础光照
如果你是一个Golang面试官,你会问哪些问题?
[redis series] redis learning 13. Redis often asks simple interview questions
SQLserver怎么插入或更新当天的星期数,bit而不是文本
在 VSCode 中调试 Jest 的测试用例,VSCode调试Jest测试用例报错basedir=$(dirname “$(echo “$0“ | sed -e ‘s,\\,/,g‘)“)解决
Idea code quality specification plug-in sonarlint
Running error: unable to find or load the main class com xxx. Application
NativeForMySQL 连接MySQL8 提示:1251- Client does not support authentication protocol
AI 视频云 VS 窄带高清,谁是视频时代的宠儿
S2-062 remote command execution vulnerability recurrence (cve-2021-31805)
第四章 为物化视图启用和禁用IM列存储(IM 4.6)
栈和队列a
第五章 使用In-Memory表达式优化查询(IM 5.1)