Balanced Binary Tree Python Solution - Beat 99.07% of Solutions

  • 0

    Recursively iterate to the bottom of the tree, and then traverse back up, checking each subtree and adding 1 to the height each move upward.

    class Solution(object):
        def isBalanced(self, root):
            :type root: TreeNode
            :rtype: bool
            ans= self.isB(root)
            if ans is not -1:
                return True
                return False
        def isB(self, root):
            if root == None:
                return 0
            leftH = self.isB(root.left)
            if leftH == -1:
                return -1
            rightH = self.isB(root.right)
            if rightH == -1:
                return -1
            if abs(leftH-rightH) > 1:
                return -1
            return 1 + max(rightH, leftH)

Log in to reply

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