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.
Subscribe to see which companies asked this question
解法一:
如果complete binary tree是full binary tree,那根据公式返回2^d-1。不然,递归的调用countNode。
/**
* 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* left = root, *right = root;
int lh =0, rh =0;
while(left){
++lh;
left = left->left;
}
while(right){
++rh;
right = right->right;
}
if(lh==rh) return pow(2,lh)-1;
return countNodes(root->left)+countNodes(root->right)+1;
}
};