给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:

输入:
1
/ \
2 3
/ \ /
4 5 6 输出: 6 转别人解法:
class Solution {
public int countNodes(TreeNode root) {
/**
完全二叉树的高度可以直接通过不断地访问左子树就可以获取
判断左右子树的高度:
如果相等说明左子树是满二叉树, 然后进一步判断右子树的节点数(最后一层最后出现的节点必然在右子树中)
如果不等说明右子树是深度小于左子树的满二叉树, 然后进一步判断左子树的节点数(最后一层最后出现的节点必然在左子树中)
**/
if (root==null) return ;
int ld = getDepth(root.left);
int rd = getDepth(root.right);
if(ld == rd) return ( << ld) + countNodes(root.right); // 1(根节点) + (1 << ld)-1(左完全左子树节点数) + 右子树节点数量
else return ( << rd) + countNodes(root.left); // 1(根节点) + (1 << rd)-1(右完全右子树节点数) + 左子树节点数量 } private int getDepth(TreeNode r) {
int depth = ;
while(r != null) {
depth++;
r = r.left;
}
return depth;
}
}

我用遍历解的:

先序/中序/后序

class Solution {
public:
int countNodes(TreeNode* root) {
if (root) {
++n;
countNodes(root->left);
//++n;
countNodes(root->right);
//++n;
}
return n;
}
private:
int n = ;
};

层次遍历:

class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> Q;
TreeNode* temp = root;
if (temp != NULL)
Q.push(temp);
while (!Q.empty()) {
temp = Q.front();
++n;
Q.pop();
if (temp->left)
Q.push(temp->left);
if (temp->right)
Q.push(temp->right);
}
return n;
}
private:
int n = ;
};
 

最新文章

  1. 字符编码和python .encode().decode()方法
  2. C#模拟键盘输入(一)
  3. Git合并特定commits 到另一个分支
  4. Reverse Pairs
  5. HttpSession--会话
  6. 从零开始学ios开发(十二):Table Views(中)UITableViewCell定制
  7. 拼写sql语句随笔
  8. Configuring Robolectric
  9. JAVA复习2 JAVA开发环境配置
  10. 哈尔滨理工大学第六届程序设计团队 H-Permutation
  11. Google Chrome即将开始警告—停止支持Flash Player
  12. python小练习1:设计这样一个函数,在桌面的文件夹上创建10个文本,以数字给它们命名。
  13. Linux学习笔记14—文件的压缩与打包
  14. R中的高效批量处理函数(lapply sapply apply tapply mapply)(转)
  15. spring MVC初始化过程学习笔记1
  16. STM32F4 External interrupts
  17. C#调试含有源代码的动态链接库遇见there is no source code available for the current location提示时的解决方案
  18. 【转载】MFC怎么封装CreateWindow
  19. 关掉firefox(火狐)和palemoon地址栏自动加www.前缀功能【转】
  20. redhat 配置本地yum源163yum源epel 源,无需卸载yum!无须拷贝ISO

热门文章

  1. Python入门:模拟登录(二)或注册之requests处理带token请求
  2. Vue国际化的使用
  3. jQuery的选择器+实例
  4. C# 快速排序--二分查找法--拉格朗日插值法
  5. 使用metasploit进行栈溢出攻击-4
  6. Glib之GObject简介(翻译)
  7. 正经学C#_变量与其数据类型:《c#入门经典》
  8. 毛玻璃CHBlurEffect
  9. oracle修改连接数
  10. js window.open()打开的页面关闭后刷新父页面