1. What I learned
try, except, else, raise
This is how to handle exceptions. ‘try’ is the action you want to try, ‘except’ is the result of an exception, and ‘else’ is the result of a normal situation. An exception can occur through ‘raise Exception()’.
try:
ACTION
except:
return ERROR RESULT
else:
return RIGHT RESULT
2. Code
class Solution:
def dfs(self, node):
if not node:
return 0
left = self.dfs(node.left) # Depth on the left
right = self.dfs(node.right) # Depth on the right
if abs(left-right) > 1: # If the difference between the depth on the left and the depth on the right is greater than 1, then the condition is not high-balance binary tree.
raise Exception()
return max(left, right) + 1
def isBalanced(self, root: TreeNode) -> bool:
try:
self.dfs(root)
except:
return False
else:
return True
3. Result
Runtime : 44 ms(92.17%), Memory usage : 18.4 MB(51.10%)
(Runtime can be different by a system even if it is a same code.)