给定一棵完全二叉树,计算它的节点数。
样例
样例1
输入: {1,2,3,4,5,6}
输出: 6
解释:
1
/ \
2 3
/ \ /
4 5 6
样例2
输入: {1,2,3,4,5,6,8}
输出: 7
解释:
1
/ \
2 3
/ \ /\
4 5 6 8
注意事项
在完全二叉树中,除了可能的最后一层之外,每层都被完全填充,并且最后一层中所有节点都尽可能地靠左。 最后一层h中,可能有1到2 ^ h个节点。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: root of complete binary tree
* @return: the number of nodes
*/
int countNodes(TreeNode * root) {
// write your code here
if(root == NULL)
return 0;
int left = countNodes(root->left);
int right = countNodes(root->right);
return left + right + 1;
}
};