leecode_222 Count Complete Tree Nodes
2016-06-07 02:56
405 查看
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.
用暴力法, recursive求会超时 O(N). 如果从某节点一直向左的高度 = 一直向右的高度, 那么以该节点为root的子树一定是complete binary tree. 而 complete binary tree的节点数,可以用公式算出 2^h - 1. 如果高度不相等, 则递归调用 return countNode(left) + countNode(right)
+ 1. 复杂度为O(h^2)
c++ 代码:
/**
* 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 l = getLeft(root) + 1;
int r = getRight(root) + 1;
if(l==r) {
return (2<<(l-1)) - 1;
} else {
return countNodes(root->left) + countNodes(root->right) + 1;
}
}
int getLeft(TreeNode* root) {
int count = 0;
while(root->left!=NULL) {
root = root->left;
++count;
}
return count;
}
int getRight(TreeNode* root) {
int count = 0;
while(root->right!=NULL) {
root = root->right;
++count;
}
return count;
}
};
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.
用暴力法, recursive求会超时 O(N). 如果从某节点一直向左的高度 = 一直向右的高度, 那么以该节点为root的子树一定是complete binary tree. 而 complete binary tree的节点数,可以用公式算出 2^h - 1. 如果高度不相等, 则递归调用 return countNode(left) + countNode(right)
+ 1. 复杂度为O(h^2)
c++ 代码:
/**
* 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 l = getLeft(root) + 1;
int r = getRight(root) + 1;
if(l==r) {
return (2<<(l-1)) - 1;
} else {
return countNodes(root->left) + countNodes(root->right) + 1;
}
}
int getLeft(TreeNode* root) {
int count = 0;
while(root->left!=NULL) {
root = root->left;
++count;
}
return count;
}
int getRight(TreeNode* root) {
int count = 0;
while(root->right!=NULL) {
root = root->right;
++count;
}
return count;
}
};
相关文章推荐
- DrawNode绘制几何图形
- node.js 和 express 框架学习笔记(2)
- node js 获取ip
- javascript中children和childNodes的区别
- Study NodeJS《NPM常用命令》
- 【LeetCode】011 Swap Nodes in Pairs 两两换位
- 《Nodejs开发加密货币》之十七:共识机制,可编程的利益转移规则
- ambari回滚 禁止namenode ha
- Folk博客程序——可以运行于node环境和asp环境的博客系统
- node定时任务
- inode与super block
- BAE log服务的配置(nodejs)
- 6个讨喜的 ES6 小技巧
- Node学习笔记(三):基于socket.io web版你画我猜(二)
- 【leetcode】25. Reverse Nodes in k-Group
- Node.js的Web模板引擎ejs的入门使用教程
- 关于nodejs邮件群发的Nodemailer
- nodejs 的 session 简单使用
- 关于nodejs接受多文件上传问题
- hadoop 错误1 journalnode与namenode超时