I am trying to solve LeetCode problem 110. Balanced Binary Tree:
Given a binary tree, determine if it is height-balanced.
Here is my attempt:
class Solution {
boolean c = true;
public boolean isBalanced(TreeNode root) {
int diff = helper(root, 0);
System.out.println(diff);
if ((diff > 0 && diff < 2) || root == null)
return true;
return false;
}
int helper(TreeNode root, int count) {
if (root == null) {
return count;
}
int a = helper(root.left, count + 1);
int b = helper(root.right, count + 1);
int diff = Math.abs(a - b);
if (diff > 1 || diff < 0)
return count;
return Math.max(a, b);
}
}
I get the wrong result for the following input:
3
/ \
9 20
/ \
15 7
Encoded in level order: [3,9,20,null,null,15,7]
The expected output is true, but my code returns false.
The TreeNode class is as follows:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
Here is the main code to reproduce it:
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode tree = new TreeNode(3,
new TreeNode(9),
new TreeNode(20,
new TreeNode(15),
new TreeNode(7)
)
);
boolean result = solution.isBalanced(tree);
System.out.println("result " + result); // false, but should be true
}
What is my mistake?