题目地址
https://leetcode.com/problems/count-complete-tree-nodes/
利用完全二叉树的性质,求一颗完整二叉树的节点总数
采用遍历所有节点的方法会超时,需要利用递归求解
思路参考
西施豆腐渣
http://blog.csdn.net/xudli/article/details/46385011
ac代码如下
/**
* 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;
int leftCnt = 0;
int rightCnt = 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
while (left != NULL){
leftCnt++;
left = left->left;
}
while (right != NULL){
rightCnt++;
right = right->right;
}
if (leftCnt == rightCnt) // 说明是一颗完全二叉树
{
return (int)pow(2, leftCnt + 1) - 1;
}
else{
return 1 + countNodes(root->left) + countNodes(root->right);
}
}
};