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;
        }
复制代码

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(125)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-04-11 pattern matching is C# 7.0
2018-04-11 托管在IIS上的wcf,在启动的时候,写log
2015-04-11 C#中的转换
点击右上角即可分享
微信分享提示