package tree.recursive;
import tree.TreeNode;
public class BalancedBinaryTree {
private static final int IMBALANCED_TREE = -1;
private int helper(TreeNode root) {
if (root == null)
return 0;
int leftDepth = helper(root.left);
if (leftDepth == IMBALANCED_TREE)
return IMBALANCED_TREE;
int rightDepth = helper(root.right);
if (rightDepth == IMBALANCED_TREE)
return IMBALANCED_TREE;
if (Math.abs(rightDepth - leftDepth) > 1)
return IMBALANCED_TREE;
return Math.max(rightDepth, leftDepth) + 1;
}
public boolean isBalanced(TreeNode root) {
return helper(root) != IMBALANCED_TREE;
}
}
package com.eureka
package tree.recursive
import tree.TreeNode
object BalancedBinaryTree:
def isBalanced(_root: TreeNode): Boolean =
def depth(root: TreeNode): Int =
if root == null then return 0
val leftDepth = depth(root.left)
val rightDepth = depth(root.right)
if leftDepth == -1 || rightDepth == -1 then -1
else if java.lang.Math.abs(leftDepth - rightDepth) > 1 then -1
else java.lang.Math.max(leftDepth, rightDepth) + 1
depth(_root) != -1