您的位置:首页 > Web前端 > Node.js

222. Count Complete Tree Nodes

2016-05-11 15:58 435 查看
Given a complete binary
tree, count the number of nodes.

计算完全二叉树的节点数目。满二叉树的节点数是2^h-1, 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==NULL) return 0;
int count = 1;
count += countNodes(root->left);
count += countNodes(root->right);
return count;
-------------------*/
if(root==NULL) return 0;
int leftH = getLeftHeight(root);
int rightH = getRightHeight(root);
if(leftH==rightH)
return (1<<leftH)-1;
else
{
return countNodes(root->left) + countNodes(root->right)+1;
}
}
int getLeftHeight(TreeNode* root)
{
if(root==NULL) return 0;
int h = 1;
while(root->left)
{
h++;
root= root->left;
}
return h;
}
int getRightHeight(TreeNode* root)
{
if(root==NULL) return 0;
int h = 1;
while(root->right)
{
h++;
root= root->right;
}
return h;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: