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.

解题思路:

计算完全二叉树节点,直接递归会TLE,一个不错的思路是判断是否为满二叉树,然后进行递归,JAVA实现如下:

    public int countNodes(TreeNode root) {
if(root==null)
return 0;
int leftHeight=1,rightHeight=1;
TreeNode temp=root.left;
while(temp!=null){
temp=temp.left;
leftHeight++;
}
temp=root.right;
while(temp!=null){
temp=temp.right;
rightHeight++;
}
if(leftHeight==rightHeight)
return (1<<leftHeight)-1;
return countNodes(root.left)+countNodes(root.right)+1;
}

最新文章

  1. 安装ganglia
  2. 微信小程序之登录态维护(十一)
  3. Blackfin DSP(四):BF533 EBIU之SDRAM
  4. java获取点击微信自定义菜单的用户openid
  5. 我发现:在StackOverflow上拯救歪果仁十分有意思!
  6. 浏览器获取ip地址
  7. 使用CSS3实现超炫的Loading(加载)动画效果
  8. VNC Server 配置
  9. jQuery 事件 方法
  10. 修真院java后端工程师学习课程--任务1(day four)
  11. 获取具有指定扩展数据的所有实体的Id,并存入Id数组中
  12. VScode查找替换常用正则表达式
  13. CodeForces 937D 936B Sleepy Game 有向图判环,拆点,DFS
  14. Codeforces Round #309 (Div. 2) -D. Kyoya and Permutation
  15. Tomcat架构解析(四)-----Coyote、HTTP、AJP、HTTP2等协议
  16. MySQL &#183; 关系模型的基本术语
  17. 25-[jQuery]-事件
  18. 在Ubuntu 12.04 桌面上设置启动器(快捷方式)
  19. UTF-8中的BOM
  20. Http请求超时的一种处理方法

热门文章

  1. jquery中的$(&quot;#id&quot;)与document.getElementById(&quot;id&quot;)的区别
  2. 如何获取客户端MAC地址(三个方法)
  3. 有感于三个50岁的美国程序员的生活状态与IT职业杂想
  4. sql拼音简写函数
  5. XMAL语法系列之-(2)---WPF控件继承图
  6. [译]git rebase -i
  7. 可编辑select
  8. VPN和SSH的原理区别
  9. JS的构造函数
  10. bootstrap-dropdown