Given a complete binary tree, count the number of nodes.

Note:

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.

Example:

Input:
1
/ \
2 3
/ \ /
4 5 6 Output: 6

这道题给定了一棵完全二叉树,让我们求其节点的个数。很多人分不清完全二叉树和满二叉树的区别,下面让我们来看看维基百科上对二者的定义:

完全二叉树 (Complete Binary Tree)

A Complete Binary Tree (CBT) is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

对于一颗二叉树,假设其深度为d(d>1)。除了第d层外,其它各层的节点数目均已达最大值,且第d层所有节点从左向右连续地紧密排列,这样的二叉树被称为完全二叉树;

换句话说,完全二叉树从根结点到倒数第二层满足完美二叉树,最后一层可以不完全填充,其叶子结点都靠左对齐。

完美二叉树 (Perfect Binary Tree)

A Perfect Binary Tree(PBT) is a tree with all leaf nodes at the same depth. All internal nodes have degree 2.

二叉树的第i层至多拥有  个节点数;深度为k的二叉树至多总共有  个节点数,而总计拥有节点数匹配的,称为“满二叉树”;

完满二叉树 (Full Binary Tree):

A Full Binary Tree (FBT) is a tree in which every node other than the leaves has two children.

换句话说,所有非叶子结点的度都是2。(只要你有孩子,你就必然是有两个孩子。)

其实这道题的最暴力的解法就是直接用递归来统计结点的个数,根本不需要考虑什么完全二叉树还是完美二叉树,递归在手,遇 tree 不愁。直接一行搞定碉堡了,这可能是我见过最简洁的 brute force 的解法了吧,参见代码如下:

解法一:

class Solution {
public:
int countNodes(TreeNode* root) {
return root ? ( + countNodes(root->left) + countNodes(root->right)) : ;
}
};

我们还是要来利用一下完全二叉树这个条件,不然感觉对出题者不太尊重。通过上面对完全二叉树跟完美二叉树的定义比较,可以看出二者的关系是,完美二叉树一定是完全二叉树,而完全二叉树不一定是完美二叉树。那么这道题给的完全二叉树就有可能是完美二叉树,若是完美二叉树,节点个数很好求,为2的h次方减1,h为该完美二叉树的高度。若不是的话,只能老老实实的一个一个数结点了。思路是由 root 根结点往下,分别找最靠左边和最靠右边的路径长度,如果长度相等,则证明二叉树最后一层节点是满的,是满二叉树,直接返回节点个数,如果不相等,则节点个数为左子树的节点个数加上右子树的节点个数再加1(根节点),其中左右子树节点个数的计算可以使用递归来计算,参见代码如下:

解法二:

class Solution {
public:
int countNodes(TreeNode* root) {
int hLeft = , hRight = ;
TreeNode *pLeft = root, *pRight = root;
while (pLeft) {
++hLeft;
pLeft = pLeft->left;
}
while (pRight) {
++hRight;
pRight = pRight->right;
}
if (hLeft == hRight) return pow(, hLeft) - ;
return countNodes(root->left) + countNodes(root->right) + ;
}
};

我们也可以全用递归的形式来解,如下所示:

解法三:

class Solution {
public:
int countNodes(TreeNode* root) {
int hLeft = leftHeight(root);
int hRight = rightHeight(root);
if (hLeft == hRight) return pow(, hLeft) - ;
return countNodes(root->left) + countNodes(root->right) + ;
}
int leftHeight(TreeNode* root) {
if (!root) return ;
return + leftHeight(root->left);
}
int rightHeight(TreeNode* root) {
if (!root) return ;
return + rightHeight(root->right);
}
};

这道题还有一个标签是 Binary Search,但是在论坛上看了一圈下来,并没有发现有经典的二分搜索的写法,只找到了下面这个类似二分搜索的解法,感觉应该不算严格意义上的二分搜素法吧,毕竟 left,right 变量和 while 循环都没有,只是隐约有点二分搜索法的影子在里面,即根据条件选左右分区。首先我们需要一个 getHeight 函数,这是用来统计当前结点的左子树的最大高度的,因为一直走的是左子结点,若当前结点不存在,则返回 -1。我们对当前结点调用 getHeight 函数,得到左子树的最大高度h,若为 -1,则说明当前结点不存在,直接返回0。否则就对右子结点调用 getHeight 函数,若返回值为 h-1,说明左子树是一棵完美二叉树,则左子树的结点个数是 2^h-1 个,再加上当前结点,总共是 2^h 个,即 1<<h,此时再加上对右子结点调用递归函数的返回值即可。若对右子结点调用 getHeight 函数的返回值不为 h-1,说明右子树一定是完美树,且高度为 h-1,则总结点个数为 2^(h-1)-1,加上当前结点为 2^(h-1),即 1<<(h-1),然后再加上对左子结点调用递归函数的返回值即可。这样貌似也算一种二分搜索法吧,参见代码如下:

解法四:

class Solution {
public:
int countNodes(TreeNode* root) {
int res = , h = getHeight(root);
if (h < ) return ;
if (getHeight(root->right) == h - ) return ( << h) + countNodes(root->right);
return ( << (h - )) + countNodes(root->left);
}
int getHeight(TreeNode* node) {
return node ? ( + getHeight(node->left)) : -;
}
};

我们也可以写成迭代的形式,用一个 while 循环,感觉好处是调用 getHeight 函数的次数变少了,因为开头计算的高度h可以一直用,每下一层后,h自减1即可,参见代码如下:

解法五:

class Solution {
public:
int countNodes(TreeNode* root) {
int res = , h = getHeight(root);
if (h < ) return ;
while (root) {
if (getHeight(root->right) == h - ) {
res += << h;
root = root->right;
} else {
res += << (h - );
root = root->left;
}
--h;
}
return res;
}
int getHeight(TreeNode* node) {
return node ? ( + getHeight(node->left)) : -;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/222

类似题目:

Closest Binary Search Tree Value

参考资料:

https://leetcode.com/problems/count-complete-tree-nodes/

https://leetcode.com/problems/count-complete-tree-nodes/discuss/61958/Concise-Java-solutions-O(log(n)2)

https://leetcode.com/problems/count-complete-tree-nodes/discuss/61953/Easy-short-c%2B%2B-recursive-solution

https://leetcode.com/problems/count-complete-tree-nodes/discuss/61948/Accepted-Easy-Understand-Java-Solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Count Complete Tree Nodes 求完全二叉树的节点个数的更多相关文章

  1. [LeetCode] 222. Count Complete Tree Nodes 求完全二叉树的节点个数

    Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree ...

  2. 222. Count Complete Tree Nodes -- 求完全二叉树节点个数

    Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from W ...

  3. LeetCode OJ:Count Complete Tree Nodes(完全二叉树的节点数目)

    Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from W ...

  4. 【leetcode】222. Count Complete Tree Nodes(完全二叉树)

    Given the root of a complete binary tree, return the number of the nodes in the tree. According to W ...

  5. LeetCode Count Complete Tree Nodes

    原题链接在这里:https://leetcode.com/problems/count-complete-tree-nodes/ Given a complete binary tree, count ...

  6. LeetCode——Count Complete Tree Nodes

    Description: Given a complete binary tree, count the number of nodes. In a complete binary tree ever ...

  7. leetcode 958. Check Completeness of a Binary Tree 判断是否是完全二叉树 、222. Count Complete Tree Nodes

    完全二叉树的定义:若设二叉树的深度为h,除第 h 层外,其它各层 (1-h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树. 解题思路:将树按照层进行遍历,如果 ...

  8. leetcode面试准备:Count Complete Tree Nodes

    1 题目 Given a complete binary tree, count the number of nodes. In a complete binary tree every level, ...

  9. 【LeetCode】222. Count Complete Tree Nodes 解题报告(Python)

    [LeetCode]222. Count Complete Tree Nodes 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个 ...

随机推荐

  1. 使用ViewPager实现自动轮播

    很多APP中都实现了类似引导页的自动轮播,不由得想到昨天的引导页上修改一下代码实现轮播. 其实大体上只需要添加一个线程循环执行就可以了. 项目已同步至:https://github.com/nanch ...

  2. yii2获取登录前的页面url地址--电脑和微信浏览器上的实现以及yii2相关源码的学习

    对于一个有登录限制(权限限制)的网站,用户输入身份验证信息以后,验证成功后跳转到登录前的页面是一项很人性化的功能.那么获取登录前的页面地址就很关键,今天在做一个yii2项目的登录调试时发现了一些很有意 ...

  3. 现代3D图形编程学习-关于本书(译)

    本书系列 现代3D图形编程学习 关于这本书 三维图像处理硬件很快成为了必不可少的组件.很多操作系统能够直接使用三维图像硬件,有些甚至要求需要有3D渲染能力的硬件.同时对于日益增加的手机系统,3D图像硬 ...

  4. NGUI学习笔记(一)UILabel介绍

    来个前言: 作为一个U3D程序员,自然要写一写U3D相关的内容了.想来想去还是从UI开始搞起,可能这也是最直观同时也最重要的部分之一了.U3D自带的UI系统,也许略坑,也没有太多介绍的价值,那么从今天 ...

  5. 定向爬虫 - Python模拟新浪微博登录

    当我们试图从新浪微博抓取数据时,我们会发现网页上提示未登录,无法查看其他用户的信息. 模拟登录是定向爬虫制作中一个必须克服的问题,只有这样才能爬取到更多的内容. 实现微博登录的方法有很多,一般我们在模 ...

  6. [deviceone开发]-动态添加组件add方法的示例

    一.简介 这个示例详细介绍ALayout的add方法的使用(原理也适用于Linearlayout),以及add上去的新ui和已有的ui如何数据交换,初学者推荐.二.效果图 三.相关下载 https:/ ...

  7. 模块化你的JS代码

    为什么要使用模块模式? 因为在全局作用域中声明的变量和函数都自动成为全局对象Window的属性,这经常会导致命名冲突,还会导致一些非常重要的可维护性难题,全局变量越多,引入错误BUG的概率就越大!所以 ...

  8. Atitit.安全性方案规划设计4gm  v1 q928

    Atitit.安全性方案规划设计4gm  v1 q928 1. 安全架构设计与功能安全检测1 2. https1 3. 账号安全体系1 4. 配置文件安全 1 5. 源码加密与安全2 6. 最高强度的 ...

  9. Scala 变长参数

    如果Scala定义变长参数 def sum(i Int*), 那么调用sum时,可以直接输入sum(1,2,3,4,5) 但是不可以sum(1 to 5) 必须要将1 to 5 强制为seq sum( ...

  10. Linux系统安装MySql步骤及截屏

    ➠更多技术干货请戳:听云博客 如下是我工作中的记录,介绍的是linux系统下使用官方编译好的二进制文件进行安装MySql的安装过程和安装截屏,这种安装方式速度快,安装步骤简单! 需要的朋友可以按照如下 ...