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) } }