【LectCode】222. Count Complete Tree Nodes
来源:互联网 发布:为什么淘宝免运费 编辑:程序博客网 时间:2024/05/29 04:37
题目:
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.
解题思路:一个完全二叉树当其最左端的节点的深度l与最右端的节点的深度r相等时,其节点数为(2^(l+1))-1;若不相等时,则其节点数等于其左子树的节点数加上右节点的节点数再加1;可以用递归来求。
解答:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL){
return 0;
}
else{
TreeNode* l = root;
int leftsize = 0,rightsize = 0;
while(l->left != NULL){
leftsize ++;
l = l->left;
}
TreeNode* r = root;
while(r->right != NULL){
rightsize ++;
r = r->right;
}
if(leftsize == rightsize){
return pow(2.0,leftsize + 1) -1;
}
else{
return countNodes(root->left) + countNodes(root->right) + 1;
}
}
}
};
- 【LectCode】222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes**
- css中的z-index属性
- hdu-1087 Super Jumping! Jumping! Jumping!
- linux 安装 jdk
- 数据库知识点复习之数据库系统概述
- 基于宝塔面板(bt)+ 阿里云ECS + WordPress 搭建个人主页(以独立博客为例)
- 【LectCode】222. Count Complete Tree Nodes
- SQL语句
- 【模板】最长上升子序列 O(nlogn)
- SpringMvc的controller是singleton的(非线程安全的)
- bzoj 4517: [Sdoi2016]排列计数(错排+组合数逆元)
- 关于nginx启动失败 [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
- 关于启动php-fpm报错 ERROR: unable to bind listening socket for address '127.0.0.1:9000': Address already
- hdu-2151 Worm
- Linux(CentOS7.1)修改默认yum源为国内的阿里云yum源