原题链接在这里:https://leetcode.com/problems/count-complete-tree-nodes/

题目:

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.

题解:

Complete Tree的定义是左右深度差不大于1.

递归调用函数,终止条件两个,一个是root == null, return 0. 另一个是左右高度相同说明是满树, return 2^height-1.

若是左右高度不同,递归调用求 左子树包含Node数 + 右子树包含Node数 + 1(自身).

Note:1. 用Math.pow(), 注意arguments 和 return type 都是double, 此处会TLE.

2. 用<<来完成幂运算,但注意<<的precedence比+,-还要低,需要加括号.

Time Complexity: O(h^2). worst case对于每一层都要求一遍当前点到leaf得深度.

假设只有最底层多了一个TreeNode 那么计算height就需要每层计算一遍h + (h-1) + (h-2) + ... + 1 = O(h^2).

Space: O(h), stack space.

AC  Java:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
TreeNode p = root;
TreeNode q = root;
int leftDepth = 0;
int rightDepth = 0;
while(p!=null){
leftDepth++;
p = p.left;
}
while(q!=null){
rightDepth++;
q = q.right;
} if(leftDepth == rightDepth){
return (1<<leftDepth) - 1;
}else{
return countNodes(root.left) + 1 + countNodes(root.right);
}
}
}

最新文章

  1. 安装.NET FRAMEWORK 4.5安装进度条回滚之后发生严重错误 代码0x80070643
  2. Lucene 工作原理 之倒排索引
  3. ACdream1157 Segments(CDQ分治 + 线段树)
  4. Nao 类人机器人 相关资料
  5. 如何写出小而清晰的函数?(JS 版)
  6. urlrewrite 地址重写
  7. select组件2
  8. 错误: 无法找到或可以不被加载到主类 Main
  9. 由max_allowed_packet引发的mysql攻防大战
  10. Virtualbox虚拟机Ubuntu共享文件夹设置 自动挂载
  11. Vsftp的PASV mode和Port模式配置文件的设置
  12. Google Cardboard的九轴融合算法——基于李群的扩展卡尔曼滤波
  13. Object类的方法
  14. Daily record-December
  15. IdentityServer4 中文文档 -12- (快速入门)添加外部认证支持
  16. Spring4.2+SpringMVC+Mybatis3.4的集成(转-)
  17. 【Android】窗口机制分析与UI管理系统
  18. 你不知道的js
  19. C# 内存理论与实践
  20. C语言动态链表数据结构

热门文章

  1. elasticsearch1.0 升级2.2的数据备份和恢复
  2. 关于UIWebView的总结
  3. HOWTO:制作 Windows 7 加速部署映像(作者:苏繁)
  4. $.each(),$.map()归纳
  5. 开发基础框架:mybatis-3.2.8 +hibernate4.0+spring3.0+struts2.3
  6. SELECT &#39;www&#39; = 0; 1
  7. w_click_twice
  8. charles 使用 技巧
  9. Abstract Algebra chapter 7
  10. python 十进制 十六进制