Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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
- * }
- fails: [1,2,2,3,null,null,3,4,null,null,4]
- */
- class Solution {
- fun isBalanced(root: TreeNode?): Boolean {
- if(root == null) return true
- val heightLeft = maxHeight(root.left, 1)
- val heightRight = maxHeight(root.right, 1)
- return Math.abs(heightLeft - heightRight) <= 1
- }
- private fun maxHeight(node: TreeNode?, h: Int): Int {
- if(node == null) return h
- return Math.max(
- maxHeight(node.left, h + 1),
- maxHeight(node.right, h + 1)
- )
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement