您的位置:首页 > Web前端 > Node.js

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: