LeetCode 110. Balanced Binary Tree

LeetCode 110. Balanced Binary Tree (平衡二叉树)

题目

链接

https://leetcode.cn/problems/balanced-binary-tree/

问题描述

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

示例

输入:root = [3,9,20,null,null,15,7]
输出:true

提示

树中的节点数在范围 [0, 5000] 内
-104 <= Node.val <= 104

思路

平衡二叉树的条件可以分为3个,左子树为avl,右子树为avl,左右子树高度相差为1或0,采用递归方法,需要增加一个函数用于计算深度。

复杂度分析

时间复杂度 O(n2)
空间复杂度 O(n)

代码

Java

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        } else {
            return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
        }
    }

    public int height(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            return Math.max(height(root.left), height(root.right)) + 1;
        }
    }
posted @ 2022-06-02 15:06  cheng102e  阅读(14)  评论(0编辑  收藏  举报