题意
给一个完全二叉树,求节点数目。
思路
首先,假设完全二叉树的深度为h,那么0到h - 1都是满的,只有h不一定是满的。
算法1
我们只需要知道最后一层的最后一个不是NULL的节点是哪一个就可以了。
我们假设最后一层的所以节点编号为[0,2n−1](n=h−1)。那么我们二分一下最后一层最后一个非NULL节点就好了。然后去判断这个节点是否存在。
在判断这个节点的时候,我们就需要知道从根节点到这个节点的路径。假设将往左走即为0,往右走即为1。那么节点的编号即为路径。比如最后一层第3个(从0开始),二进制表示为011,那么只需要从根节点左→右→右的走即可。
算法2
利用二叉树本身已经二分 + 满二叉树的性质。
假设我们当前节点为p,p的极左节点(从p一直往左走)的深度等于p的极右节点(从p一直往右走)的深度,那么就说明以p为根节点的子树是一个满二叉树,节点数目可以直接计算不用再搜。
代码
//algorithm1
/**
* 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 findDepth(TreeNode *p) {
if (p == NULL) return 0;
return 1 + findDepth(p->left);
}
bool has(int x, TreeNode *p, int dep) {
dep -= 2; //if dep == 1 || dep == 0
while (dep >= 0) {
if (x & (1 << dep)) p = p->right;
else p = p->left;
dep--;
}
return p;
}
int countNodes(TreeNode* root) {
int dep = findDepth(root);
//num is coding from 0 to 2^n - 1
int l = 0, r = (1 << dep - 1) - 1, m = 0, ans = 0;
while (l <= r) {
m = l + (r - l >> 1);
if (has(m, root, dep)) l = m + 1, ans = m;
else r = m - 1;
}
return dep > 0 ? (1 << (dep - 1)) + ans : 0;
}
};
//algorithm 2
/**
* 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) {
if (!root) return 0;
int hl = 1, hr = 1;
TreeNode *l = root, *r = root;
while (l->left) {hl++; l = l->left;}
while (r->right) {hr++; r = r->right;}
if (hl == hr) return (1 << hl) - 1;
return 1 + countNodes(root->left) + countNodes(root->right);
}
};

本文介绍两种高效算法来计算完全二叉树中的节点数量。一种是通过二分查找找到最后一层最后一个非空节点的位置;另一种是利用二叉树的特性直接计算满二叉树的节点数。

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



