Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 13x 36x 13x 7x 6x 1x 5x | import type { TreeNode } from './Tree'
export default function isBalanced(root: TreeNode<number> | null): boolean {
const depth = (root: TreeNode<number> | null): number => {
return root === null ? 0 : Math.max(depth(root.left), depth(root.right)) + 1
}
if (root === null)
return true
if (Math.abs(depth(root.left) - depth(root.right)) > 1)
return false
return isBalanced(root.left) && isBalanced(root.right)
}
|