完全二叉树的节点个数
问题描述
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
提示:
树中节点的数目范围是[0, 5 * 104]
0 <= Node.val <= 5 * 104
题目数据保证输入的树是 完全二叉树
示例
示例 1:
输入:root = [1,2,3,4,5,6]
输出:6
示例 2:
输入:root = []
输出:0
示例 3:
输入:root = [1]
输出:1
解题思路
已知:
1. 完全二叉树可视为由若干个满二叉树组成。
2. 一颗满二叉树,若已知其深度为h,则其结点总数为2^h-1。
根据以上两个条件思考出如下解题步骤:
1. 后序遍历该二叉树,对二叉树的每个结点进行如下操作:
1.1 判断以当前结点为根结点的二叉树是否为满二叉树
1.2 若是,则直接返回该满二叉树的结点数,且不再递归处理该结点下的子节点
1.3 若不是,则递归处理该结点下的子节点,最后返回 (1 + 左子树结点数 + 右子树结点数)
代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int getNum(TreeNode root) {
if (root == null) {
return 0;
}
//从当前结点向左向右搜索当前二叉树,若左右两个方向得到的深度相同则当前二叉树为满二叉树
int leftDepth = 0;
int rightDepth = 0;
TreeNode temp = root;
while (temp.left != null) {
leftDepth++;
temp = temp.left;
}
temp = root;
while (temp.right != null) {
rightDepth++;
temp = temp.right;
}
if (leftDepth == rightDepth) {
//直接返回该满二叉树的结点数
return (int)Math.pow(2, leftDepth + 1) - 1;
} else {
//递归处理左右节点
int leftNum = getNum(root.left);
int rightNum = getNum(root.right);
return leftNum + rightNum + 1;
}
}
public int countNodes(TreeNode root) {
return getNum(root);
}
}
}
public int countNodes(TreeNode root) {
return getNum(root);
}
}