1. problem
balance tree, left - right height not more than 1
subtree fit this rule
2. init class Solution : def isBalanced (self, root: Optional[TreeNode] ) -> bool:
3. thought
get each node’s left/right height. do math.
if unbalance happened in farthest node, O(n^2)
4. trouble
n^2
-1 is really useful
5.final solution class Solution : def isBalanced (self, root: Optional[TreeNode] ) -> bool: if not root: return True if abs (self.depth(root.left) - self.depth(root.right)) > 1 : return False return self.isBalanced(root.left) and self.isBalanced(root.right) def depth (self, root: Optional[TreeNode] ) -> int: if not root: return 0 return 1 + max (self.depth(root.left) , self.depth(root.right) )
Nice, but worst case go trought n node, n depth compare in each node, find Flase in farthest node.
but if we check any falut balance from bottom, we only go trough n node. and make use of -1 in number.
class Solution : def isBalanced (self, root: Optional[TreeNode] ) -> bool: return self.depth(root) != -1 def depth (self, root: Optional[TreeNode] ) -> int: if not root: return 0 leftDepth = self.depth(root.left) if leftDepth == -1 : return -1 rightDepth = self.depth(root.right) if rightDepth == -1 : return -1 if abs (leftDepth - rightDepth) > 1 : return -1 return 1 + max (self.depth(root.left) , self.depth(root.right) )