LeetCode 110 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
public class BalancedBinaryTree {
public boolean isBalanced(TreeNode root) {
return method(root).isBalance;
}
public class ResultDate {
int high;
boolean isBalance;
public ResultDate() {
}
public ResultDate(int high, boolean isBalance) {
this.high = high;
this.isBalance = isBalance;
}
}
public ResultDate method(TreeNode root) {
if (null == root) {
return new ResultDate(0, true);
}
ResultDate leftResultDate = method(root.left);
ResultDate rightResultDate = method(root.right);
int high = Math.max(leftResultDate.high, rightResultDate.high) + 1;
boolean isBalance = false;
if ((Math.abs(leftResultDate.high - rightResultDate.high) < 2) && leftResultDate.isBalance && rightResultDate.isBalance) {
isBalance = true;
}
return new ResultDate(high, isBalance);
}
}
评论区