Doragd / Algorithm

基于GitHub Action和GitHub Issue功能记录LeetCode刷题记录

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

110. 平衡二叉树

Doragd opened this issue · comments

110. 平衡二叉树

  • 给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
  • 递归定义法:按照定义法来做
    • 问题分解: 求高度, 然后求是否平衡
    • 递归定义: 一颗高度平衡二叉树的左子树是平衡的;右子树是平衡的; 再判断这个子结构是否是平衡的
class Solution {
public:
    //问题分解: 求高度, 然后求是否平衡
    //递归定义: 一颗高度平衡二叉树的左子树是平衡的;右子树是平衡的; 再判断这个子结构是否是平衡的
    int getMaxDepth(TreeNode* root){
        if(!root) return 0;
        return max(
            getMaxDepth(root->left), getMaxDepth(root->right)
        ) + 1;
    }
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        bool flag = isBalanced(root->left) & isBalanced(root->right);
        if(!flag) return false; 
        return abs(getMaxDepth(root->left)-getMaxDepth(root->right)) <= 1;
    }
};