原题地址:https://leetcode-cn.com/problems/count-complete-tree-nodes/submissions/
题目描述:
给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例:
输入:
1
/ \
2 3
/ \ /
4 5 6
输出: 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) {
if(!root) return 0;
int leftDepth = 1;//最左边的叶子结点深度
int rightDepth = 1;//最右边的叶子结点的深度
TreeNode* tmp = root;
while (tmp->left){
leftDepth ++;
tmp = tmp->left;
}
tmp = root;
while (tmp->right){
rightDepth ++;
tmp = tmp->right;
}
if(leftDepth==rightDepth) //是满二叉树
return (1 << leftDepth) - 1;
return countNodes(root->left) + countNodes(root->right) + 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) {
TreeNode *p=root;
int n=0;
while(p) ++n,p=p->right;
int l=(1<<n)-1,r=(1<<(n+1))-2;
while(l<r){
int mid=(l+r+1)>>1;
p=root;
for(int k=n-1;k>=0;--k)
if(mid&(1<<k)) p=p->right;
else p=p->left;
if(p) l=mid;
else r=mid-1;
}
return l;
}
};