题目:
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.
代码:
/**
* 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 ;
int hl = ;
TreeNode* l = root->left;
int hr = ;
TreeNode* r = root->right;
while ( l ){
++hl;
l = l->left;
}
while ( r ){
++hr;
r = r->right;
}
if ( hr==hl ) return pow(, hr)-;
return Solution::countNodes(root->left) + Solution::countNodes(root->right) + ;
}
};
tips:
学习大神的递归代码:http://bookshadow.com/weblog/2015/06/06/leetcode-count-complete-tree-nodes/
(1)如果left height=right height则是full tree可以直接返回节点数
(2)如果left height!=right height则不是full tree,分别递归求解left和right的节点数