今天都是递归版本,迭代版本还需要再学习学习
题目链接:110. 平衡二叉树 - 力扣(LeetCode)
思路:平衡二叉树就是一个左右子树的高度差都不大于1的二叉树。那么就可以把它转化为求二叉树的深度最后加一个判断就好
int getDepth(struct TreeNode* root){
if(root == NULL){
return 0;
}
//不需要进行左右结点是否为空的判断,因为如果为空的话,会返回数值0
//if(root->left)
int ld = getDepth(root->left);
//if(root->right)
int rd = getDepth(root->right);
int depth = ld > rd ? ld + 1 : rd +1;
return depth;
}
bool isBalanced(struct TreeNode* root) {
if(root == NULL){
return true;
//不是return 0 因为 这是在判断函数中不是在计算深度的函数中
}
//分别求左右子树的高度
int ld = getDepth(root->left);
int rd = getDepth(root->right);
//求左右子树的高度差
int sub = ld - rd;
if(sub > 1 || sub < -1){
return 0;
}
//该节点的左右孩子看成左右子树的根节点继续这样重复的判断
return isBalanced(root->left) && isBalanced(root->right);
}
题目链接:111. 二叉树的最小深度 - 力扣(LeetCode)
思路:二叉树的最小深度是根节点到最近的叶子节点的最短路径上的结点个数
一定要是叶子节点,什么是叶子节点,左右孩子同时为空的结点就是叶子结点。
int getDepth(struct TreeNode *root){
if(root == NULL){
return 0;
}
int ld = getDepth(root->left);
int rd = getDepth(root->right);
if(root->left != NULL && root->right == NULL){
return ld + 1;
}
if(root->left == NULL && root->right != NULL){
return rd + 1;
}
int depth = ld > rd ? rd : ld;
return depth + 1;
}
int minDepth(struct TreeNode* root) {
return getDepth(root);
}
题目链接:222. 完全二叉树的节点个数 - 力扣(LeetCode)
思路:对于完全二叉树又有满完全二叉树和非满完全二叉树
区分:左子树右子树的高度相等是一棵满完全二叉树 否则是一棵非满完全二叉树
满完全二叉树的结点个数:2^n-1个 n是满完全二叉树的高度,减一是因为根结点那一层只有一个结点
非满完全二叉树的结点个数:左子树的结点个数与右子树的结点个数相加最后再加一,再加一是因为要算上根节点
int countNodes(struct TreeNode* root) {
int ld = 0, rd = 0;
struct TreeNode* left = root->left;
struct TreeNode* right = root->right;
while(left){
left = left->left;
ld++;
}
while(right){
right = right->right;
rd++;
}
if(ld == rd){
return (2 << ld) - 1;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}