110 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:true
示例 2:
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
示例 3:
输入:root = []
输出:true
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/balanced-binary-tree
解决方案:
提供思路
通过递归判断是否为平衡二叉树
上代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution
{
public bool IsBalanced(TreeNode root)
{
if (root == null)
{
return true;
}
return CompareHeight(root) != -1;
}
public int CompareHeight(TreeNode root)
{
if (root == null)
{
return 0;
}
int left = CompareHeight(root.left);
int right = CompareHeight(root.right);
if (left == -1 || right == -1 || Math.Abs(left - right) > 1)
{
return -1;
}
return Math.Max(left, right) + 1;
}
}
以上是碰到的第一百一十题,后续持续更新。感觉对你有帮助的小伙伴可以帮忙点个赞噢!

186

被折叠的 条评论
为什么被折叠?



