题目
- 完全二叉树的节点个数
给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例:
输入:
1
/ \
2 3
/ \ /
4 5 6
输出: 6
题解
方法一:DFS法
思路:对于任何二叉树都可以试用,遍历数结点,到达一个结点+1,返回最后的总数
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
//方法一:普通递归法
if(root == null){
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
方法二:BFS
思路:先计算树的高度height,然后计算右子树的高度,如果右子树的高度等于height - 1,说明左子树是满二叉树,可以通过公式(2^(height - 1)) - 1计算即可,不需要全部遍历,然后通过递归的方式计算右子树。如果右子树的高度不等于height - 1,说明右子树是满二叉树,不过少了一层,就是height- 2 ,也可以通过公式计算,然后在通过递归的方式计算左子树。
class Solution{
public int countNodes(TreeNode root) {
//计算树的高度,
int height = treeHeight(root);
//如果树是空的,或者高度是1,直接返回
if (height == 0 || height == 1)
return height;
//如果右子树的高度是树的高度减1,说明左子树是满二叉树,
//左子树可以通过公式计算,只需要递归右子树就行了
if (treeHeight(root.right) == height - 1) {
//注意这里的计算,左子树的数量是实际上是(1 << (height - 1))-1,
//不要把根节点给忘了,在加上1就是(1 << (height - 1))
return (1 << (height - 1)) + countNodes(root.right);
} else {
//如果右子树的高度不是树的高度减1,说明右子树是满二叉树,可以通过
//公式计算右子树,只需要递归左子树就行了
return (1 << (height - 2)) + countNodes(root.left);
}
}
//计算树的高度
private int treeHeight(TreeNode root) {
return root == null ? 0 : 1 + treeHeight(root.left);
}
}