方法一:自顶向下的递归
# 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 = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def dfs(node):
if not node:
return 0
l = dfs(node.left)
r = dfs(node.right)
return max(l, r) + 1
if not root:
return True
if not self.isBalanced(root.left) or not self.isBalanced(root.right):
return False
return True if abs(dfs(root.left) - dfs(root.right)) <= 1 else False
方法二:自底向上的递归
# 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 = right
class Solution:
def dfs(self, node):
if not node:
return 0
l = self.dfs(node.left)
r = self.dfs(node.right)
if abs(l - r) > 1 or l == -1 or r == -1:
return -1
else:
return max(l, r) + 1
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
return self.dfs(root) > 0