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)
        }
    }
  • 相关阅读:
    [汇编与C语言关系]1.函数调用
    深入理解计算机系统
    设计模式
    深度探索C++对象模型
    More Effective C++
    MySQL必知必会
    数据结构与算法分析
    Java编程思想(后)
    Java编程思想(前十章)
    Java 入门
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15001226.html
Copyright © 2011-2022 走看看