110. Balanced Binary Tree

时间:2021-07-12
本文章向大家介绍110. Balanced Binary Tree,主要包括110. Balanced Binary Tree使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
package LeetCode_110

/**
 * 110. Balanced Binary Tree
 * https://leetcode.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.
 * */
class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

class Solution {
    /*
    Solution: find the max height of each node.
    * Time complexity:O(nlogn), Space complexity:O(n)
    * */
    fun isBalanced(root: TreeNode?): Boolean {
        if (root == null)
            return true
        if (root.left == null && root.right == null)
            return true
        val leftDeep = getDeep(root.left)
        val rightDeep = getDeep(root.right)
        if (Math.abs(leftDeep - rightDeep) > 1)
            return false
        return isBalanced(root.left) && isBalanced(root.right)
    }

    fun getDeep(node: TreeNode?): Int {
        if (node == null)
            return 0
        val leftHeight = getDeep(node.left)
        val rightHeight = getDeep(node.right)
        return 1 + Math.max(leftHeight, rightHeight)
    }
}

原文地址:https://www.cnblogs.com/johnnyzhao/p/15001226.html