题目:
Count Complete Tree Nodes
Given a complete binary tree, count the number of nodes.
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.
分析:
解法来源自脑客爱刷题,时间复杂度是 O(h^2) ,h是二叉树的高度。
总体思路是:判断当前节点的右子树是不是满二叉树。若是,则返回 “左子树的节点总数+1(当前节点)+右子树的节点总数(用公式算)”,若不是,则返回 “左子树的节点总数(用公式算)+1(当前节点)+右子树的节点总数”。若当前节点的右孩子为空,则特殊对待。
/**
* 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==nullptr)
return 0;
return countNodes_core(root,1,most_left_height(root,1));
}
//root节点是第level层(从1开始数),all是二叉树的总的层数
//返回值是以root为根的二叉树的节点总数
int countNodes_core(TreeNode* root,int level,int all)
{
//level==all 意味着这是叶子节点
if(level==all)
{
return 1;
}
if(root->right)
{
int tmp= most_left_height(root->right,level+1);
if(tmp==all)
{
return 1+(1<<(all-level))-1+countNodes_core(root->right,level+1,all);
}
else
{
return 1+(1<<(all-level-1))-1+countNodes_core(root->left,level+1,all);
}
}
//右子树为空,只有一种可能:root是倒数第二层,且其左子树不为空
else
{
return 2;
}
}
//root节点是第level层(从1开始数),返回的是root最左下角的节点的层数
int most_left_height(TreeNode* root,int level)
{
int high=level;
TreeNode* cur=root;
while(cur->left!=nullptr)
{
++high;
cur=cur->left;
}
return high;
}
};