---
title: "[leetcode] Balanced Binary Tree"
author: "standalone"
date: "2013-04-28T14:08:57Z"
tags: []
categories: ["编程语言"]
slug: "leetcode-balanced-binary-tree"
draft: false
lastmod: "2013-04-28T14:08:57Z"
id: 1856516
url: "https://standalone.iteye.com/blog/1856516"
---

Check if a binary tree is balanced or not. This solution is from the discuss board. Much better than mine.


```java

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        return height(root) != -1;
    }

    private int height(TreeNode root)
    {
        if(root == null)
            return 0;

        int leftHeight = height(root.left);
        if(leftHeight == -1)
            return -1;

        int rightHeight = height(root.right);
        if(rightHeight == -1)
            return -1;

        if(Math.abs(leftHeight - rightHeight) > 1)
            return -1;

        return 1 + Math.max(leftHeight, rightHeight);
    }
}
```