# Time : O(n), Space : O(n) # Post Order classSolution(object): defmaxDepth(self, root): ifnot root: return0 left = self.maxDepth(root.left) right = self.maxDepth(root.right) return max(left,right) + 1
A binary tree in which the depth of the two subtrees of every node never differ by more than 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Time : O(nlogn), Space : O(n) classSolution(object): defheight(self, root): ifnot root: return0 return max(self.height(root.left), self.height(root.right)) + 1
defisBalanced(self, root): ifnot root: returnTrue left = self.height(root.left) right = self.height(root.right) if abs(left-right) > 1: returnFalse return self.isBalanced(root.left) and self.isBalanced(root.right)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Time : O(n), Space : O(n) classSolution(object): defisBalanced(self, root): return self.dfs(root) != -1
defdfs(self, root): ifnot root: return0 left = self.dfs(root.left) if left == -1: return-1
right = self.dfs(root.right) if right == -1: return-1