zoukankan      html  css  js  c++  java
  • 110. Balanced Binary Tree

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as:

    a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    Example 1:

    Given the following tree [3,9,20,null,null,15,7]:

        3
       / 
      9  20
        /  
       15   7

    Return true.

    Example 2:

    Given the following tree [1,2,2,3,3,null,null,4,4]:

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:

    它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树

     public bool IsBalanced(TreeNode root)
            {
                if (root == null)
                {
                    return true;
                }
                int maxLeftDepth = MaxDepth(root.left);
                int maxRightDepth = MaxDepth(root.right);
                bool flag1 = Math.Abs(maxLeftDepth - maxRightDepth) <= 1;
                bool flag2 = IsBalanced(root.left);
                bool flag3 = IsBalanced(root.right);
                return flag1 && flag2 && flag3;
            }
    
            public int MaxDepth(TreeNode root)
            {
                int depth;
                if (root == null)
                {
                    depth = 0;
                }
                else
                {
                    depth = 1;
                    TreeNode left = root.left;
                    TreeNode right = root.right;
                    if (left != null || right != null)
                    {
                        int leftDepth = MaxDepth(left);
                        int rightDepth = MaxDepth(right);
                        depth = depth + Math.Max(leftDepth, rightDepth);
                    }
                }
    
                return depth;
            }
  • 相关阅读:
    CSS的一些单位,如rem、px、em、vw、vh、vm
    js判断浏览器的类型
    VUE项目引入jquery
    安装搭配VUE使用的UI框架ElementUI
    VUE环境搭建,项目配置(Windows下)
    纯CSS写的各种小三角和小箭头
    改变input的placeholder字体颜色
    LR
    使用WebKit.net加载HTML编辑器
    c# 打开指定的网址
  • 原文地址:https://www.cnblogs.com/chucklu/p/10689027.html
Copyright © 2011-2022 走看看