leetcode 日经贴,Cpp code -Count Complete Tree Nodes
2015-06-08 11:50
651 查看
Count Complete Tree Nodes
/** * 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 countHeight(TreeNode *r, bool le) { if (!r) return 0; if (le) { return countHeight(r->left, le) + 1; } else { return countHeight(r->right, le) + 1; } } bool checkNode(TreeNode *r, int s, int h) { if (h < 0) return r? true:false; if (!r) return false; if (s & (1 << h)) { return checkNode(r->right, s, h - 1); } else { return checkNode(r->left, s, h - 1); } } int countNodes(TreeNode* root) { int hl = countHeight(root, true); int hr = countHeight(root, false); if (hl == hr) { return (1 << hl) - 1; } int low = 0, high = (1<<hr) - 1, mid; while (low < high) { mid = (low + high) / 2; if (checkNode(root, mid, hr - 1)) { low = mid + 1; } else { high = mid; } } return (1 << hr) - 1 + low; } };
相关文章推荐
- 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
- Populating Next Right Pointers in Each Node I, II
- npm and node 的一些问题
- [leetcode][tree] Count Complete Tree Nodes
- inode理解
- 磁盘inode不足,使用xfs文件系统
- LeetCode Count Complete Tree Nodes
- leetcode[19]:Remove Nth Node From End of List Total
- node.js中关于使用formidable模块实现文件上传至指定目录的问题
- NodeJS中的NPM代理设置
- [LeetCode][JavaScript]Count Complete Tree Nodes
- Count Complete Tree Nodes
- nodejs版本更新问题:express不是内部或外部命令
- nodejs版本更新问题:express不是内部或外部命令
- LeetCode Count Complete Tree Nodes