[leetcode] Count Complete Tree Nodes
2015-06-08 21:45
253 查看
From : 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.
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 leftLevel(TreeNode* node) { if(!node) return 0; int level = 1, num; while(node->left) { level++; node = node->left; } return level; } int rightLevel(TreeNode* node) { if(!node) return 0; int level = 1, num; while(node->right) { level++; node = node->right; } return level; } int countNodes(TreeNode* root) { if(!root) return 0; int ll = leftLevel(root); int rl = rightLevel(root); if(ll == rl) return (1<<ll)-1; return 1 + countNodes(root->left) + countNodes(root->right); } };
相关文章推荐
- Count Complete Tree Nodes
- Sublime2 运行NodeJS
- LeetCode 25: Reverse Nodes in k-Group
- [LeetCode] Count Complete Tree Nodes
- 升级 node 版本
- 谁才是性能之王?( Node.js vs io.js v2.0.0 )
- LeetCode_24---Swap Nodes in Pairs
- 用链表实现nodejs的内存对象管理
- Node.js是一个事件驱动I/O服务端JavaScript环境
- puppet学习笔记之node/package/service/file/user/group/cron/exec管理
- IIS部署Nodejs步骤
- Hadoop中namenode/datanone没有启动
- nodejs - 如何完全更新
- leetcode 日经贴,Cpp code -Count Complete Tree Nodes
- Hadoop集群中启动namenode失败的解决办法
- leetcode 24 -- Swap Nodes in Pairs
- root.sh Fails on the First Node for 11gR2 Grid Infrastructure Installation
- node.js学习总结(不定期更新)
- nodejs express 框架使用
- Hadoop集群安全性:Hadoop中Namenode单点故障的解决方案及详介AvatarNode