【LeetCode】110. 平衡二叉树

题目

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

示例 1:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / 
  9  20
    /  
   15   7

返回 true 。

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

       1
      / 
     2   2
    / 
   3   3
  / 
 4   4

返回 false 。

本题同【剑指Offer】面试题55 - II. 平衡二叉树

思路一:自上到下

代码

时间复杂度:O(n^2)
空间复杂度:O(nlogn)

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (!root) {
            return true;
        }
        int left = depth(root->left);
        int right = depth(root->right);
        if (abs(left-right) > 1) {
            return false;
        }
        return isBalanced(root->left) && isBalanced(root->right);
    }
    int depth(TreeNode *root) {
        if (!root) {
            return 0;
        }
        int left = depth(root->left);
        int right = depth(root->right);
        return max(left, right)+1;
    }
};

思路二:自下到上

代码

时间复杂度:O(n)

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (!root) {
            return true;
        }
        int dfsdepth = depth(root);
        return dfsdepth != -1;
    }
    int depth(TreeNode *root) {
        if (!root) {
            return 0;
        }
        int left = depth(root->left);
        if (left == -1) {
            return -1;
        }
        int right = depth(root->right);
        if (right == -1) {
            return -1;
        }
        if (abs(left-right) > 1) {
            return -1;
        }
        return max(left, right)+1;
    }
};
原文地址:https://www.cnblogs.com/galaxy-hao/p/12392978.html