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);
}
};
/**
* 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);
}
};
相关文章推荐
- Delete Node in a Linked List 单链表删除节点
- NodeJS 读取XML文件
- LeetCode2.2.9(Reverse Nodes in k-Group)
- LeetCode2.2.8(Swap Nodes in Pairs)
- LeetCode2.2.7(Remove Nth Node From End of List)
- 在Ubuntu上安装Node.js的Upstream版本
- Delete Node in a Linked List
- LeetCode Remove Nth Node From End of List
- LeetCode Remove Nth Node From End of List
- windows下使用Nodejs开发Express4.x
- Remove Nth Node From End of List
- 解读Nodejs多核处理模块cluster
- LeetCode(237) Delete Node in a Linked List
- Node.js进程通信模块child_process
- nodepad++的emmet的使用问题
- NodeJs文件操作备注
- nodejs初步了解
- [leetcode] 19.Remove Nth Node From End of List
- nodejs 处理表单上传文件时,获取不到表单数据
- node.js和websocket实现echo