LeetCode – Balanced Binary Tree (Java)

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.

Analysis

This is a typical tree problem that can be solve by using recursion.

Java Solution

// Definition for binary tree
class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;
 
	TreeNode(int x) {
		val = x;
	}
}
 
public class Solution {
	public boolean isBalanced(TreeNode root) {
		if (root == null)
			return true;
 
		if (getHeight(root) == -1)
			return false;
 
		return true;
	}
 
	public int getHeight(TreeNode root) {
		if (root == null)
			return 0;
 
		int left = getHeight(root.left);
		int right = getHeight(root.right);
 
		if (left == -1 || right == -1)
			return -1;
 
		if (Math.abs(left - right) > 1) {
			return -1;
		}
 
		return Math.max(left, right) + 1;
 
	}
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Ankit Shah

    public static boolean isBalanced(TreeNode root) {
    return (maxdepth(root) – mindepth(root) < 2);
    }

    private static int maxdepth(TreeNode root) {
    if (root == null) {
    return 0;
    }
    return 1 + Math.max(maxdepth(root.left), maxdepth(root.right));
    }

    private static int mindepth(TreeNode root) {
    if (root == null) {
    return 0;
    }
    return 1 + Math.min(mindepth(root.left), mindepth(root.right));

  • Parth Solanki

    No need to call getHeight(root.right) if getHeight(root.left) returns -1. Do this instead:

    int left = getHeight(root.left);
    if (left = -1) return return -1;

    int right = getHeight(root.right);
    if (right = -1) return return -1;

  • Neel Sheyal

    Take the root. Compute the height of its left and right sub tree.

    If the difference between height of the left and right sub tree is less than or equal to 1, return true.

    Otherwise, return false.

    Repeat these two steps for each node in the given binary tree.
    We can optimize the above algorithm and solve the problem in linear time. Instead of computing the height at each level, we can compute it in the same recursion.

    For explanation and code http://www.algoqueue.com/algoqueue/default/view/8912896/check-binary-tree-balanced-or-not

  • lcheng

    Height would be 1 if there is only one node. You will reach the null node and return 0+1;

  • Dhvl

    In case if we have only one node (the root node), height according to your function is 1 where as it should be zero. Correct me if I am wrong. Thanks