110. 平衡二叉树
难度:简单
题目描述
解题思路
这个题好像做过的样子
自底向上可以避免很多重复的运算
自底向上
/*
* 110. 平衡二叉树
* 2020/8/17
*/
public boolean isBalanced(TreeNode root) {
return isBalancedHelper(root) == -1;
}
public int isBalancedHelper(TreeNode root) {
if(root == null)
return 0;
int left = isBalancedHelper(root.left);
int right = isBalancedHelper(root.right);
if(left == -1 || right == -1) {
return -1;
}
if(Math.abs(left-right) < 2) { //返回最大的左右子树的高度
return Math.max(left, right)+1;
}else {
return -1;
}
}
自顶向下
感觉就是求二叉树最大深度的翻版,会产生很多重复计算
//自顶向下
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
int left = isBalancedHelper(root.left);
int right = isBalancedHelper(root.right);
return Math.abs(left-right) < 2 && isBalanced(root.left) && isBalanced(root.right);
}
public int isBalancedHelper(TreeNode root) {
if(root == null)
return 0;
int left = isBalancedHelper(root.left);
int right = isBalancedHelper(root.right);
return Math.max(left, right)+1;
}