Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Java Solution:
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Result {
boolean val;
Result() {
this.val = true;
}
public void setValue(boolean val) {
this.val = val;
}
public boolean getValue() {
return val;
}
}
class Solution {
public boolean isBalanced(TreeNode root) {
Result isBalanced = new Result();
getHeight(root, isBalanced);
return isBalanced.getValue();
}
private int getHeight(TreeNode node, Result isBalanced) {
if (node == null) return 0;
int leftHeight = getHeight(node.left, isBalanced);
int rightHeight = getHeight(node.right, isBalanced);
if (Math.abs(leftHeight - rightHeight) > 1) {
isBalanced.setValue(false);
}
return Math.max(leftHeight, rightHeight) + 1;
}
}
Essentially, trying to “hack” the pass-by-reference C++ has into the Java solution. But it solves the problem in one pass.