跟着carl学算法,本系列博客仅做个人记录,建议大家都去看carl本人的博客,写的真的很好的!
代码随想录
LeetCode:110.平衡二叉树
给定一个二叉树,判断它是否是
平衡二叉树
示例 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
在一个递归里面即取求高度也去判断是否平衡
public boolean isBalanced(TreeNode root) {return getHeight(root) != -1;}private int getHeight(TreeNode root) {if (root == null)return 0;int leftHeight = getHeight(root.left);if (leftHeight == -1)return -1;int rithtHeight = getHeight(root.right);if (rithtHeight == -1)return -1;int res = 0;if (Math.abs(leftHeight - rithtHeight) > 1)return -1;elsereturn 1 + Math.max(leftHeight, rithtHeight);}