完全二叉树的节点个数
给你一棵完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例 1:
输入:root = [1,2,3,4,5,6]
输出:6
示例 2:
输入:root = []
输出:0
示例 3:
输入:root = [1]
输出:1
提示:
树中节点的数目范围是[0, 5 * 104]
0 <= Node.val <= 5 * 104
题目数据保证输入的树是 完全二叉树
直接用求普通二叉树的深度(递归)
递归三部曲:
- 确定递归函数的参数和返回值
- 确定终止条件
- 确定单层递归的逻辑
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int getNodesNum(TreeNode *cur)
{
if(cur == NULL) return 0;
int leftNum = getNodesNum(cur->left);
int rightNum = getNodesNum(cur->right);
int treeNum = leftNum+rightNum+1;
return treeNum;
}
public:
int countNodes(TreeNode* root) {
return getNodesNum(root);
}
};
使用完全二叉树性质递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == nullptr) 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++;
}
//判断是否为满二叉树 即左递归深度和右递归深度
//如果是 则深度为 2^h -1
if(leftDepth == rightDepth)
{
return (2<<leftDepth)-1;//因为leftDepth是从0开始计数 h=leftDepth+1 2<<1 = 2^2
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};
平衡二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int getHeight(TreeNode* node)
{
//单层递归的逻辑
if(node == nullptr)
{
return 0;
}
int leftHeight = getHeight(node->left);//以该节点为根节点的二叉树高度
if(leftHeight == -1) return -1;
int rightHeight = getHeight(node->right);
if(rightHeight == -1) return -1;
return abs(leftHeight-rightHeight) > 1 ? -1 : 1+max(leftHeight,rightHeight);
}
public:
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
烦死了、、、、、、