题目描述
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
一、对应任意二叉树都适用
(1)递归法
我们从递归三要素分析:
递归三要素
调用参数和返回值
终止情况
递归逻辑
- 首先,依据题意,我们需要返回一个int类型的数据。至于参数则是树的根节点 TreeNode* root
- 当前节点为空则返回;
- 递归逻辑::先求它的左子树的节点数量,再求右子树的节点数量,最后取总和再加一 (加1是因为算上当前中间节点)就是目前节点为根节点的节点数量。
代码如下:
普通二叉树
//递归
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == NULL)return 0;
int leftNum = countNodes(root->left);
int rightNum = countNodes(root->right);
return leftNum + rightNum + 1;
}
};
(2)迭代法:
将层序遍历的方法稍加改进,即可求得二叉树的节点个数。
层序遍历
//层序法
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
if(root!=NULL) que.push(root);
int res = 0;
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
res++;
if (node->left)que.push(node->left);
if (node->right)que.push(node->right);
}
}
return res;
}
};
二、完全二叉树的特性
完全二叉树只有两种情况,情况一:就是满二叉树,情况二:最后一层叶子节点没有满。
对于情况一,可以直接用 2^树深度 - 1 来计算,注意这里根节点深度为1。
对于情况二,分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后依然可以按照情况1来计算。
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == NULL)return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftDepth = 0;
int rightDepth = 0;
while (left) {
left=left->left;
leftDepth++;
}
while (right) {
right = right->right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
};