day21-110.平衡二叉树

110.平衡二叉树

力扣题目链接

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

返回 false 。

知识准备

这里要强调一些概念,什么是深度又什么是高度。

  • 深度:根节点到叶子结点的距离
  • 高度:叶子节点到根节点的距离

用一张图会更加直观

对于深度和高度的求法,各有不同,求深度应该从上到下,使用前序遍历 ,而高度是从下到上,应该是后序遍历

在之前的求二叉树的最大深度时,使用的是后序,原因是求的是叶子节点的深度,也为根节点的高度。

如果是正经用前序遍历求深度,代码如下:

cpp 复制代码
class Solution {
private:
    int res;
public:
    void getDepth(TreeNode* node, int depth){
        res = max(res,depth);
        if(node->left == nullptr && node->right == nullptr)return ;

        if(node->left){
            depth++;
            getDepth(node->left,depth);
            depth--;
        }
        if(node->right){
            depth++;
            getDepth(node->right,depth);
            depth--;
        }
        return;
    }
    int maxDepth(TreeNode* root) {
        res = 0;
        if(root == nullptr)return res;
        getDepth(root,1);
        return res;
    }
};

思路

首先确定我们要求的应该是高度,使用后序遍历。

  • 确定终止条件

if(root == null)return 0

返回0则是高度为0

  • 单层循环

确定终止条件后,分别求左右子树的高度。

cpp 复制代码
		int leftHeight = getHeight(root->left);
        if(leftHeight == -1)return -1;
        int rightHeight = getHeight(root->right);
        if(rightHeight == -1)return -1;
  • 确定高度差
cpp 复制代码
		int res = 0;
        res = abs(leftHeight-rightHeight) > 1?-1:1+max(leftHeight,rightHeight);
        return res;

最终代码如下:

cpp 复制代码
class Solution {
public:
    int getHeight(TreeNode* root){
        if(root == nullptr)return 0;
        
        int leftHeight = getHeight(root->left);
        if(leftHeight == -1)return -1;
        int rightHeight = getHeight(root->right);
        if(rightHeight == -1)return -1;

        int res = 0;
        res = abs(leftHeight-rightHeight) > 1?-1:1+max(leftHeight,rightHeight);
        return res;
    }
    bool isBalanced(TreeNode* root) {
        return getHeight(root) == -1?false:true;
    }
};

eturn res;

}

bool isBalanced(TreeNode* root) {

return getHeight(root) == -1?false:true;

}

};

复制代码
相关推荐
Hello_Embed12 小时前
FreeRTOS 入门(四):堆的核心原理
数据结构·笔记·学习·链表·freertos·
烧冻鸡翅QAQ13 小时前
考研408笔记——数据结构
数据结构·笔记·考研
异步的告白13 小时前
C语言-数据结构-2-单链表程序-增删改查
c语言·开发语言·数据结构
Gorgous—l14 小时前
数据结构算法学习:LeetCode热题100-图论篇(岛屿数量、腐烂的橘子、课程表、实现 Trie (前缀树))
数据结构·学习·算法
热心市民小刘050516 小时前
11.18二叉树中序遍历(递归)
数据结构·算法
未若君雅裁16 小时前
LeetCode 18 - 四数之和 详解笔记
java·数据结构·笔记·算法·leetcode
小欣加油17 小时前
leetcode 429 N叉树的层序遍历
数据结构·c++·算法·leetcode·职场和发展
星轨初途18 小时前
《数据结构二叉树之堆 —— 优先队列与排序的高效实现(2)(下)》
c语言·开发语言·数据结构·经验分享·笔记·性能优化
高山有多高19 小时前
堆应用一键通关: 堆排序 +TOPk问题的实战解析
c语言·数据结构·c++·算法
前进之路920 小时前
Leetcode每日一练--47
数据结构·算法·leetcode