sanya5791

Balanced Binary Tree (not working)

Jul 29th, 2021
954
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Example:
  3.  * var ti = TreeNode(5)
  4.  * var v = ti.`val`
  5.  * Definition for a binary tree node.
  6.  * class TreeNode(var `val`: Int) {
  7.  *     var left: TreeNode? = null
  8.  *     var right: TreeNode? = null
  9.  * }
  10. fails: [1,2,2,3,null,null,3,4,null,null,4]
  11.  */
  12. class Solution {
  13.    
  14.     fun isBalanced(root: TreeNode?): Boolean {
  15.         if(root == null) return true
  16.        
  17.         val heightLeft = maxHeight(root.left, 1)
  18.         val heightRight = maxHeight(root.right, 1)
  19.         return Math.abs(heightLeft - heightRight) <= 1
  20.     }
  21.    
  22.     private fun maxHeight(node: TreeNode?, h: Int): Int {
  23.         if(node == null) return h
  24.        
  25.         return Math.max(
  26.             maxHeight(node.left, h + 1),
  27.             maxHeight(node.right, h + 1)
  28.         )
  29.     }
  30. }
RAW Paste Data