Leetcode-标签为Tree 110. Balanced Binary Tree

来源:互联网 发布:网络摄像机排行榜 编辑:程序博客网 时间:2024/06/06 03:49

原题

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.

题目分析

判断二叉树是否为平衡二叉树。

代码实现

 public class BanlancedTree    {        public bool IsBalanced(TreeNode root)        {            if (root == null)                return true;            if (Math.Abs(height(root.left) - height(root.right)) > 1)                return false;            return IsBalanced(root.left) && IsBalanced(root.right);        }        private int height(TreeNode node)        {            if (node == null)                return 0;            return 1 + Math.Max(height(node.left), height(node.right));        }    }
1 0
原创粉丝点击