Python recursive compute depth and check


  • 0
    def isBalanced(self, root):
            if root is None:
                return True
            if self.depth(root, 1) is not False:
                return True
            else:
                return False
    
    def depth(self, root, d):
            if root.left is None and root.right is None:
                return d
            else:
                if root.left is not None and root.right is not None:
                    l = self.depth(root.left, d + 1)
                    r = self.depth(root.right, d + 1)
                    if l is False or r is False:
                        return False
                    elif abs(l - r) > 1:
                        return False
                    return max(l, r)
                elif root.left is not None:
                    l = self.depth(root.left, d + 1)
                    if abs(l - d) > 1:
                        return False
                    return l
                else:
                    r = self.depth(root.right, d + 1)
                    if abs(r - d) > 1:
                        return False
                    return r
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.