`
standalone
  • 浏览: 597959 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

[leetcode] Balanced Binary Tree

阅读更多
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);
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics