【Count Complete Tree Nodes】cpp
2024-08-29 21:48: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.
代码:
/**
* 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 ) return ;
int hl = ;
TreeNode* l = root->left;
int hr = ;
TreeNode* r = root->right;
while ( l ){
++hl;
l = l->left;
}
while ( r ){
++hr;
r = r->right;
}
if ( hr==hl ) return pow(, hr)-;
return Solution::countNodes(root->left) + Solution::countNodes(root->right) + ;
}
};
tips:
学习大神的递归代码:http://bookshadow.com/weblog/2015/06/06/leetcode-count-complete-tree-nodes/
(1)如果left height=right height则是full tree可以直接返回节点数
(2)如果left height!=right height则不是full tree,分别递归求解left和right的节点数
最新文章
- pandas.DataFrame对行和列求和及添加新行和列
- STM32F105解密STM32F105VB芯片解密STM32F105R8单片机破解多少钱?
- ionic中的service简单写法
- c++写入txt文件
- ASP.NET MVC2中Controller向View传递数据的三种方式
- 济南学习 Day 4 T1 pm
- 如何用正则匹配后缀名不为.jpg, .css, .js, .html, .htm, .png的文件
- 敏捷软件开发之TDD(一)
- hessian原理解析一(客户端分析)
- DOM4J介绍与代码示例
- jQuery杂项方法
- java.net.BindException: Cannot assign requested address: bind
- Android 根据字符串动态获取资源ID
- OBS studio最新版配置鉴权推流
- wcf_first
- angular的一些东西
- Bootstrap模态框原理分析及问题解决
- Linux -- 利用 ptrace 进行代码注入
- C# 实现表单的自动化测试<;通过程序控制一个网页>;
- JavaScript面向对象之函数构造器的理解
热门文章
- java研发常见问题总结 1
- AD的命名规则 AD常用产品型号命名规则
- mysql轮廓总结
- 【转】普及一下ARM和X86的区别,鉴于ATOM已经入驻手机,AMD也会…
- Intel MKL 多线程设置
- git fetch和push的区别
- convolution,fft, 加速
- eclipse环境Dynamic web module version 3.1版本的进步,简化Dynamic web object 中Servlet类的配置,不用web.xml配置<;Servlet>;
- Selenium页面加载策略
- Redis ----------String的操作