每日算法题【二叉树】:二叉树的最大深度、翻转二叉树、平衡二叉树

(13)二叉树的最大深度
  • [104. 二叉树的最大深度 - 力扣(LeetCode)](https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/)\]:

    递归思路:二叉树的最大深度等于左右子树中深度大的+1

    c 复制代码
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    
    //二叉树的最大深度等于左右子树中深度大的+1
    int maxDepth(struct TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        //使用变量保存递归回来的结果进行比较
        int leftDepth = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
    
        return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
    
    }

(14)翻转二叉树
  • [226. 翻转二叉树 - 力扣(LeetCode)](https://leetcode.cn/problems/invert-binary-tree/description/)\]:

c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* flipTree(struct TreeNode* root) {
    if (root == NULL) {
        return NULL;
    }
    
    // 交换左右子树
    struct TreeNode* temp = root->left;
    root->left = root->right;
    root->right = temp;
    
    // 递归翻转左右子树
    flipTree(root->left);
    flipTree(root->right);
    
    return root;
}

(15)判断一颗树是否是平衡二叉树
  • 110. 平衡二叉树 - 力扣(LeetCode)

  • 解题思路:

    要保证当前树的左右子树高度差不大于1,并且子树本身也是平衡树。

    1. maxDepth函数:递归计算二叉树的高度。
    2. isBalanced函数
      • 如果树为空,返回true
      • 计算左右子树的高度差
      • 如果高度差≤1且左右子树都是平衡的,返回true
      • 否则返回false
    c 复制代码
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    
    //二叉树的最大深度等于左右子树中深度大的+1
    int maxDepth(struct TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        //使用变量保存递归回来的结果进行比较
        int leftDepth = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
    
        return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
    }
    
    //通过前序遍历二叉树的最大深度来进行判断
    bool isBalanced(struct TreeNode* root) {
    
        if(root == NULL){
            return true;
        }
    
        int leftDepth = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
    
        //首先要保证当前树的左右子树高度差不大于1,并且子树本身也是平衡树。
        if(abs(leftDepth - rightDepth)<=1 && isBalanced(root->left) && isBalanced(root->right)){
            return true;
        }
    
        return false;
    }
相关推荐
云泽8084 小时前
深入解析数据结构之单链表
数据结构
西红柿维生素5 小时前
Junior Engineer浅谈CAS
java·开发语言·数据结构
lxl13075 小时前
学习数据结构(15)插入排序+选择排序(上)
数据结构·学习·排序算法
CoovallyAIHub5 小时前
GQNN 框架:让 Python 开发者轻松搭建量子神经网络
深度学习·算法·计算机视觉
CoovallyAIHub5 小时前
轻量级注意力模型HOTSPOT-YOLO:无人机光伏热异常检测新SOTA,mAP高达90.8%
深度学习·算法·计算机视觉
一尘之中5 小时前
量子计算:从抽象算法到物理实现的跨学科革命
算法·ai写作·量子计算
Xの哲學6 小时前
Linux 定时器:工作原理与实现机制深入分析
linux·服务器·算法·架构·边缘计算
Jooolin6 小时前
大名鼎鼎的哈希表,真的好用吗?
数据结构·c++·ai编程
葫三生6 小时前
三生原理的“阴阳元”能否构造新的代数结构?
前端·人工智能·算法·机器学习·数学建模