https://labuladong.gitbook.io/algo/shu-ju-jie-gou-xi-lie/wan-quan-er-cha-shu-jie-dian-shu
https://leetcode-cn.com/problems/count-complete-tree-nodes/
// 获取完全二叉树所有节点的个数,当然可以遍历一遍效率比较低
int TreeSearch::countNodes(TreeNode* root)
{
if (root == NULL)
return 0;
int hl = 0, hr = 0;
TreeNode* l = root->left;
TreeNode* r = root->right;
while (l != NULL)
{
hl++;
l = l->left;
}
while (r != NULL)
{
hr++;
r = r->left; // 注意这里是一直向左找
}
if (hl == hr)
{
return (1 << hl) + countNodes(root->right); // 左子树是完全二叉树,右子树是非完全二叉树。每一层的个数
}
// 如果hl != hr,那么hr 一定是小于hl的,去掉最下一层(按照左子节点遍历),在加上上面N层的完全二叉树
return pow(2, hr) + countNodes(root->left) + 1;
}
问题2,求完全二叉树的叶子节点数
// 获取完全二叉树的子节点数目 时间复杂度是 O(logN*logN)
int TreeSearch::getFullTreeHeight(TreeNode* root)
{
if (root == NULL)
return 0;
int hl = 0, hr = 0;
TreeNode* l = root->left;
TreeNode* r = root->right;
if (l == NULL && r == NULL)
return 1; // 如果是叶子节点的话
while (l != NULL)
{
hl++;
l = l->left;
}
while (r != NULL)
{
hr++;
r = r->right; // 一直向左找,一直向右找
}
if (hl == hr) // 相同,表示是一颗高度相同的满二叉树
{
return pow(2, hl);// 2 的 h 次幂。也可以把1向左移h位
}
return getFullTreeHeight(root->left) + getFullTreeHeight(root->right);
}