方法一:
# Definition for a binary tree node.class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = Noneclass Solution: def checkHeight(self, root:TreeNode): if root is None: return 0 else: return 1 + max(self.checkHeight(root.left), self.checkHeight(root.right)) def isBalanced(self, root: TreeNode) -> bool: # base case if TreeNode is None: return True h1 = self.checkHeight(root.left) h2 = self.checkHeight(root.right) if abs(h1 - h2) > 1: return False else: return self.isBalanced(root.left) and self.isBalanced(root.right)
思路
自定向下遍历结点, 计算该节点左右child高度差
存在的问题
isBalanced 是自顶向下的 pre-order , checkHeight 是 post-order , 存在结点高度重复计算的问题
方法二
# Definition for a binary tree node.class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = Noneclass Solution: def checkHeight(self, root: TreeNode): # base case if root is None: return 0 h1 = self.checkHeight(root.left) h2 = self.checkHeight(root.right) if h1 == -1 or h2 == -1 or abs(h1 - h2) > 1: return -1 return 1 + max(h1, h2) def isBalanced(self, root: TreeNode) -> bool: # base case return True if self.checkHeight(root) > 0 else False
思路
- 在计算高度的时候, 已经计算了平衡的信息, 于是将
isBlanced 的先序改成后序, 并合在高度计算过程中。