There are some things that smell about this code, for instance multiple checking, length
both returning value and changing some other variable. But I can't for the moment figure how to make it nicer, or if that's even possible. Converting it to stack-based solution seems to be making it a bit too-complicated.
Please provide a review of this code, what do you think could be improved, if possible, both in terms of readability and performance or possible problems.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
boolean isBalanced = true;
public boolean isBalanced(TreeNode root) {
length(root);
return isBalanced;
}
public int length(TreeNode a) {
if (a == null) {
return 0;
}
if (isBalanced == false) {
return 0;
}
int x = length(a.left);
if (isBalanced == false) {
return 0;
}
int y = length(a.right);
if (isBalanced == false) {
return 0;
}
if (Math.abs(x - y) > 1) {
isBalanced = false;
return 0;
}
return Math.max(x, y) + 1;
}
}
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.