当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.110.Balanced Binary Tree 是否平衡二叉树

LeetCode.110.Balanced Binary Tree 是否平衡二叉树

题目描述

110 Balanced Binary Tree
https://leetcode-cn.com/problems/balanced-binary-tree/

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 left and right subtrees of every node differ in height by no more than 1.

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

    3
   / \
  9  20
    /  \
   15   7

Return true.

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

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.


解题过程

类似求二叉树的高度 LeetCode.104.MaximumDepthOfBinaryTree
只不过在递归的过程中,就可以判断当前子树是否平衡,如果不平衡直接返回负值快速失败结束计算。

private static class SolutionV2020 {
    public boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }

    // 计算树的高度,同时判断是否平衡二叉树。若是平衡树返回树高度,若非平衡树返回负值
    private int height(TreeNode root) {
        if (null == root) {
            return 0;
        }
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        // 左右子树非平衡树,或者左右子树高度差大于1,则当前树不是平衡树
        if (leftHeight < 0 || rightHeight < 0 || Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }
        return Math.max(leftHeight, rightHeight) + 1;
    }
}

GitHub代码

algorithms/leetcode/leetcode/_110_BalancedBinaryTree.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_110_BalancedBinaryTree.java


上一篇 LeetCode.111.Minimum Depth of Binary Tree 二叉树的最小深度

下一篇 LeetCode.108.Convert Sorted Array to Binary Search Tree 升序数组转BST

阅读
评论
294
阅读预计1分钟
创建日期 2020-01-25
修改日期 2020-01-25
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论