【LectCode】222. Count Complete Tree Nodes

来源:互联网 发布:为什么淘宝免运费 编辑:程序博客网 时间:2024/05/29 04:37

题目:

Given a complete binary tree, count the number of nodes.

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.

解题思路:一个完全二叉树当其最左端的节点的深度l与最右端的节点的深度r相等时,其节点数为(2^(l+1))-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 == NULL){
    return 0;
}
else{
TreeNode* l = root;
int leftsize = 0,rightsize = 0;
while(l->left != NULL){
leftsize ++;
l = l->left; 

TreeNode* r = root;
while(r->right != NULL){
rightsize ++;
r = r->right; 
}
if(leftsize == rightsize){
return pow(2.0,leftsize + 1) -1;
}
else{
return countNodes(root->left) + countNodes(root->right) + 1;
}
}

    }
    
};