Balanced Binary Tree

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 depth of the two subtrees of every node never differ by more than 1.

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public boolean isBalanced(TreeNode root) {
  12. return getHeight(root) >= 0;
  13. }
  14. int getHeight(TreeNode root) {
  15. if (root == null)
  16. return 0;
  17. int left = getHeight(root.left);
  18. if (left < 0)
  19. return -1;
  20. int right = getHeight(root.right);
  21. if (right < 0)
  22. return -1;
  23. if (Math.abs(left - right) > 1)
  24. return -1;
  25. return 1 + Math.max(left, right);
  26. }
  27. }