https://leetcode.com/problems/count-complete-tree-nodes/
Given a complete binary tree, count the number of nodes.
Note:
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.Example:
Input: 1 / \ 2 3 / \ / 4 5 6 Output: 6
根据完全二叉树的性质,只需要知道层数和最后一层的节点的个数就可以计算出整棵树的结点个数。
算最后一层节点的个数如果使用层次遍历则开销过大(甚至可以直接加出来树结点个数)
因此不知怎么就想到了用数字的每一位比特表示逐层深入的决策过程,然后使用二分搜索找到最后一层最右侧结点的路径,然后就可以计算出来了
/**
* 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 countNodes(TreeNode* root) {
static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();
if(root == NULL) return 0;
int dep = 0;
TreeNode *cur = root;
while(cur->left != NULL){
++dep;
cur = cur->left;
}
if(dep == 0) return 1;
// cout << "dep: " << dep << endl;
int lo = 0, hi = (1 << dep)-1;
while(lo < hi){
int mid = (lo+hi+1)/2;
int mask = (1 << (dep-1));
cur = root;
int cnt = 0;
while(cur != NULL){
++cnt;
if(mid & mask){
cur = cur->right;
}else{
cur = cur->left;
}
mask >>= 1;
}
if(cnt == dep+1) lo = mid;
else hi = mid-1;
}
// cout << "lo: " << lo << endl;
int mask = (1 << (dep-1));
int lef = 0;
int result = 0;
int cur_lev = 1;
while(mask){
result += cur_lev;
cur_lev *= 2;
lef *= 2;
if(lo & mask){
lef += 1;
}
mask >>= 1;
}
// cout << "left: " << left << endl;
// cout << "result: " << result << endl;
result += (lef+1);
return result;
}
};
博客围绕LeetCode上计算完全二叉树节点数量的问题展开。指出根据完全二叉树性质,知道层数和最后一层节点数可算出总数。但用层次遍历算最后一层节点开销大,于是想到用数字比特表示决策过程,通过二分搜索找最后一层最右侧结点路径来计算。
396

被折叠的 条评论
为什么被折叠?



