I'm trying to solve one algorithmic problem from leetcode.
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 depth of the two subtrees of every node never differ by more than 1.
My approach is to collect the depths of the nodes and compare them. When the difference is smaller than 1 (abs), then return 1, else return False. When there is not root replace it with 0.
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root or not root.left and not root.right:
return 0
a = self.isBalanced(root.left)
b = self.isBalanced(root.right)
if abs(a-b)<=1:
return 1 + max(a,b)
else:
return False
return True
Unfortunately, the solution fails on a very primitive [] empty test input. Which is unclear to me. I thought that when there are no children, there's nothing to compare, hence 0. Am I missing smth from the definition of height-balanced tree?