zoukankan      html  css  js  c++  java
  • 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)
        }
    }
  • 相关阅读:
    systemd管理服务
    卷积神经网络
    matplotlib-3.2.1
    pandas-1.0.3
    numpy-1.18.4
    降维
    无监督学习-聚类
    集成学习
    人工神经网络
    贝叶斯分类
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15001226.html
Copyright © 2011-2022 走看看