最初的问题在这里附加了:https://leetcode.com/problems/balanced-binary-tree/description/
public class BalancedBinaryTree {
static boolean balance = true;
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
return (Math.abs(depth(root.left) - depth(root.right)) <= 1) && balance;
}
public int depth(TreeNode root) {
if (balance) {
if (root == null)
return 0;
int lengthOfLeft = depth(root.left);
int lengthOfRight = depth(root.right);
if (Math.abs(lengthOfLeft - lengthOfRight) > 1) {
balance = false;
}
return Math.max(lengthOfLeft, lengthOfRight) + 1;
} else {
return 0;
}
}
尝试一下。基本上,您应该将平衡重置回真实,因为从输出为正的测试(期望为true)到负面的测试(期望为frese)将很重要。
static boolean balance = true;
public boolean isBalanced(TreeNode root) {
balance = true;
if (root == null)
return true;
return (Math.abs(depth(root.left) - depth(root.right)) <= 1) && balance;
}
public int depth(TreeNode root) {
if (balance) {
if (root == null)
return 0;
int lengthOfLeft = depth(root.left);
int lengthOfRight = depth(root.right);
if (Math.abs(lengthOfLeft - lengthOfRight) > 1) {
balance = false;
}
return Math.max(lengthOfLeft, lengthOfRight) + 1;
} else {
return 0;
}
}