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

Leetcode 222: Count Complete Tree Nodes

2015-08-29 16:51 519 查看
Do only the recursion will cause TLE. Thus, at each node, count the heights of its left subtree and right subtree, if left height equals to the right height, the number of nodes of this root can be calculated in the mathematical way.

/**
* 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 0;
int hl=0,hr=0;
TreeNode *l=root->left,*r=root->right;
while(l)
{
l=l->left;
hl++;
}
while(r)
{
r=r->right;
hr++;
}
if(hl==hr)
return (1<<hl+1)-1;//equals to pow(2,hl+1)-1,increase the speed
return 1+countNodes(root->left)+countNodes(root->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: