题目:

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的节点数

最新文章

  1. pandas.DataFrame对行和列求和及添加新行和列
  2. STM32F105解密STM32F105VB芯片解密STM32F105R8单片机破解多少钱?
  3. ionic中的service简单写法
  4. c++写入txt文件
  5. ASP.NET MVC2中Controller向View传递数据的三种方式
  6. 济南学习 Day 4 T1 pm
  7. 如何用正则匹配后缀名不为.jpg, .css, .js, .html, .htm, .png的文件
  8. 敏捷软件开发之TDD(一)
  9. hessian原理解析一(客户端分析)
  10. DOM4J介绍与代码示例
  11. jQuery杂项方法
  12. java.net.BindException: Cannot assign requested address: bind
  13. Android 根据字符串动态获取资源ID
  14. OBS studio最新版配置鉴权推流
  15. wcf_first
  16. angular的一些东西
  17. Bootstrap模态框原理分析及问题解决
  18. Linux -- 利用 ptrace 进行代码注入
  19. C# 实现表单的自动化测试<通过程序控制一个网页>
  20. JavaScript面向对象之函数构造器的理解

热门文章

  1. java研发常见问题总结 1
  2. AD的命名规则 AD常用产品型号命名规则
  3. mysql轮廓总结
  4. 【转】普及一下ARM和X86的区别,鉴于ATOM已经入驻手机,AMD也会…
  5. Intel MKL 多线程设置
  6. git fetch和push的区别
  7. convolution,fft, 加速
  8. eclipse环境Dynamic web module version 3.1版本的进步,简化Dynamic web object 中Servlet类的配置,不用web.xml配置<Servlet>
  9. Selenium页面加载策略
  10. Redis ----------String的操作