Balanced Binary Tree - Kotlin

Balanced Binary Tree - Kotlin

·

1 min read

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.

Example 1:

balance_1.jpeg

Input: root = [3,9,20,null,null,15,7]

Output: true

Example 2:

balance_2.jpeg

Input: root = [1,2,2,3,3,null,null,4,4]

Output: true

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
class Solution {
    fun isBalanced(root: TreeNode?): Boolean {
        if(root == null) 
            return true
        else {
            val left = findDepth(root?.left)
            var right = findDepth(root?.right)
            println(left)
            println(right)
            return (Math.abs(left- right) <= 1) && isBalanced(root?.left) && isBalanced(root?.right)
        }
    }

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

}