ITeye博客

[leetcode] Balanced Binary Tree

standalone · 2013-04-28 14:08 · java · algorithm · 编程语言 · Markdown

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


/**
 * 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);
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。