110. Balanced Binary Tree

Easy
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.

submit 1:


Screen Shot 2017-09-02 at 9.23.01 AM.png

AC:


Screen Shot 2017-09-02 at 9.21.14 AM.png

最后的判断条件是该节点的左子树右子树高度差不超过1, 并且左子树和右子树也都是 Balanced Binary Tree.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null){
            return true;
        }
        int diff =  Math.abs(helper(root.left) - helper(root.right));
        if (diff > 1){
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }
    
    private int helper(TreeNode head){
        if (head == null){
            return 0;
        }
        if (head.left == null && head.right == null){
            return 1;
        }
        return Math.max(helper(head.left), helper(head.right)) + 1;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容