110. Balanced Binary Tree

Description

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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

tree

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

tree

Return false.

Solution

DFS, time O(n), space O(h)

/**
 * 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;
        }
        
        return isBalanced(root.left) && isBalanced(root.right)
            && Math.abs(depth(root.left) - depth(root.right)) <= 1;
    }
    
    private int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        return 1 + Math.max(depth(root.left), depth(root.right));
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,173评论 0 10
  • 台风在北海过境。 窗外大雨如注,浓密雨脚如麻的雨脚在海湾肆虐。起了风,闪电照亮红色天幕。惊起的炸雷像火柴点亮了黑暗...
    凹凸世界的格瑞阅读 1,733评论 0 0
  • 我,是我的第二个人格,为什么我是二呢,因为老子让他啊,老子看着他真的很不爽啊,没错,他就是我的第一人格,一个天天规...
    九里归一阅读 2,394评论 0 0
  • What?!这种想法简直太可怕了! 难怪你总会遇到渣男呢! 你想人群中能主动搭讪的男的不到10%,而这10%中又有...
    野生数学家阅读 5,538评论 0 2
  • 今天是又一次读林文采老师的《心理营养》,早晨在群里分享了两篇推荐序和林老师的自序。 感受最大的是---父母与孩子的...
    赵一桐咨询师阅读 2,394评论 0 0

友情链接更多精彩内容