zoukankan      html  css  js  c++  java
  • 【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;
        }
    };
    
  • 相关阅读:
    Node_JS
    读JS高级——第五章-引用类型 _记录
    读JS高级(兼容&&BOM&&私有变量&&面向对象)
    JS高级设计第七章——复习知识点
    nodeJs抓取网页
    表单脚本api_contenteditable
    泛——复习js高级第三版
    nodeJS
    Eclipse布局问题小记
    再议负载均衡算法
  • 原文地址:https://www.cnblogs.com/galaxy-hao/p/12392978.html
Copyright © 2011-2022 走看看