Count Complete Tree Nodes LeetCode Java
2015-06-23 11:55
567 查看
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 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.
public class Solution { public int countNodes(TreeNode root) { if(root==null) return 0; int h=height(root); if(height(root.right)==h-1){ return (1<<(h-1))+countNodes(root.right); }else return (1<<(h-2))+countNodes(root.left); } private int height(TreeNode root){ return root==null?0:1+height(root.left); } }
相关文章推荐
- 使用Node.js为其他程序编写扩展的基本方法
- Windows系统下Node.js的简单入门教程
- 使用Raygun对Node.js应用进行错误处理的方法
- Nodejs环境与express框架
- linode VPS购买、设置教程
- leetcode--Populating Next Right Pointers in Each Node II
- 使用Raygun对Node.js应用进行错误处理的方法
- Windows系统下Node.js的简单入门教程
- 使用Node.js为其他程序编写扩展的基本方法
- 使用Meteor配合Node.js编写实时聊天应用的范例
- 充分发挥Node.js程序性能的一些方法介绍
- 浅析Node.js中的内存泄漏问题
- Python和Node.js总监
- nodeJs 初探 ~
- socket.io + nodes 实现webSocket消息提醒
- UnitNode API
- InitialWordNode API
- WordNode API
- HMMNode API
- leetcode 222 Count Complete Tree Nodes (计算完全二叉树节点数)