Write maxDepth function to get the max depth of left and right subtrees
In main function, recusive to see each layer's balance and compute left and right maxDepth difference
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defisBalanced(self,root: TreeNode) ->bool:# edge caseif root ==None:returnTrue# regular caseifabs(self.maxHeight(root.left) - self.maxHeight(root.right))>1:returnFalsereturn self.isBalanced(root.left)and self.isBalanced(root.right)defmaxHeight(self,root):if root ==None:return0returnmax(self.maxHeight(root.left), self.maxHeight(root.right))+1
Solution 2:
Help function: if one of left and right subtree is not balanced, or max depth difference > 1, return -1; otherwise return maxDepth.
Main function: return true or false according to help function.
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defisBalanced(self,root: TreeNode) ->bool:return self.getHeight(root)!=-1defgetHeight(self,root):# edge caseif root ==None:return0# regular case left = self.getHeight(root.left) right = self.getHeight(root.right)if left ==-1or right ==-1:return-1ifabs(left - right)>1:return-1returnmax(left, right)+1