力扣110:判断二叉树是否为平衡二叉树

news/2024/10/7 16:00:02 标签: leetcode, 数据结构, 算法

利用二叉树遍历的思想编写一个判断二叉树,是否为平衡二叉树

示例 :

输入:root = [3,9,20,null,null,15,7]
输出:true

思想:

代码:

int getDepth(struct TreeNode* node) {
    //如果结点不存在,返回0
    if(node==NULL)
        return 0;
    //求出右子树深度
    int rightDepth = getDepth(node->right);
    //求出左子树深度
    int leftDepth = getDepth(node->left);
    //返回左右子树中的较大值+1
    return rightDepth > leftDepth ? rightDepth + 1 : leftDepth + 1;
}

bool isBalanced(struct TreeNode* root) {
    //递归结束条件为:传入结点为NULL,返回True
    if(root==NULL)
        return true;
    //求出左右子树的深度
    int leftDepth = getDepth(root->left);
    int rightDepth = getDepth(root->right);
    //若左右子树绝对值差距大于1,返回False
    if(abs(leftDepth - rightDepth) > 1 )
        return false;
    //检查左右子树是否为平衡二叉树
    return isBalanced(root->right) && isBalanced(root->left);
}

时间复杂度O(n);空间复杂度O(1) 


http://www.niftyadmin.cn/n/5693026.html

相关文章

【深度学习基础模型】液态状态机(Liquid State Machines, LSM)详细理解并附实现代码。

【深度学习基础模型】液态状态机(Liquid State Machines, LSM)详细理解并附实现代码。 【深度学习基础模型】液态状态机(Liquid State Machines, LSM)详细理解并附实现代码。 文章目录 【深度学习基础模型】液态状态机&#xff0…

初始项目托管到gitee教程,开箱即用

0.本地仓库与远程仓库关联(需先在gitee创建仓库) ①打开powershell生成ssh key ssh-keygen -t ed25519 -C "Gitee SSH Key"-t key 类型-C 注释 生成成功如下,并按下三次回车 ②查看公私钥文件 ls ~/.ssh/输出: id_…

解决npm install安装出现packages are looking for funding run `npm fund` for details问题

当我们运行npm install时,可能会收到类似以下的提示信息:"x packages are looking for funding." 这并不是错误提示,也不会影响项目的正常运行。相反,这是提醒您,有一些软件包正在寻求资金支持。 这个提示的…

Linux的发展历史与环境

目录: 引言Linux的起源早期发展企业级应用移动与嵌入式系统现代计算环境中的Linux结论 引言 Linux,作为开源操作系统的代表,已经深刻影响了全球的计算环境。从其诞生之初到如今成为服务器、嵌入式系统、移动设备等多个领域的核心&#xff0c…

C语言 | Leetcode C语言题解之第459题重复的子字符串

题目&#xff1a; 题解&#xff1a; bool kmp(char* query, char* pattern) {int n strlen(query);int m strlen(pattern);int fail[m];memset(fail, -1, sizeof(fail));for (int i 1; i < m; i) {int j fail[i - 1];while (j ! -1 && pattern[j 1] ! pattern…

Java之String类

目录 初识String 字符串比较相等 字符串常量池 理解字符串的不可变 字符与字符串 字符串常见操作 字符串比较 compareTo()函数的原码 字符串查找 字符串替换 字符串拆分 字符串截取 其它操作 StringBuffer和StringBuilder 面试题&#xff1a;请解释String、Strin…

C++面试速通宝典——14

220. static关键字的作用 ‌‌‌‌  static关键字在编程中有多种作用&#xff1a; 在类的成员变量前使用&#xff0c;表示该变量属于类本身&#xff0c;而不是任何类的实例。在类的成员函数前使用&#xff0c;表示该函数不需要对象实例即可调用&#xff0c;且只能访问类的静…

LeetCode 134 Gas Station 解题思路和python代码

题目&#xff1a; There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i 1)th station. You …