方法一:

  1. # Definition for a binary tree node.
  2. class TreeNode:
  3. def __init__(self, x):
  4. self.val = x
  5. self.left = None
  6. self.right = None
  7. class Solution:
  8. def checkHeight(self, root:TreeNode):
  9. if root is None:
  10. return 0
  11. else:
  12. return 1 + max(self.checkHeight(root.left), self.checkHeight(root.right))
  13. def isBalanced(self, root: TreeNode) -> bool:
  14. # base case
  15. if TreeNode is None:
  16. return True
  17. h1 = self.checkHeight(root.left)
  18. h2 = self.checkHeight(root.right)
  19. if abs(h1 - h2) > 1:
  20. return False
  21. else:
  22. return self.isBalanced(root.left) and self.isBalanced(root.right)

思路

  • 自定向下遍历结点, 计算该节点左右child高度差

    存在的问题

  • isBalanced 是自顶向下的 pre-order , checkHeightpost-order , 存在结点高度重复计算的问题

方法二

  1. # Definition for a binary tree node.
  2. class TreeNode:
  3. def __init__(self, x):
  4. self.val = x
  5. self.left = None
  6. self.right = None
  7. class Solution:
  8. def checkHeight(self, root: TreeNode):
  9. # base case
  10. if root is None:
  11. return 0
  12. h1 = self.checkHeight(root.left)
  13. h2 = self.checkHeight(root.right)
  14. if h1 == -1 or h2 == -1 or abs(h1 - h2) > 1:
  15. return -1
  16. return 1 + max(h1, h2)
  17. def isBalanced(self, root: TreeNode) -> bool:
  18. # base case
  19. return True if self.checkHeight(root) > 0 else False

思路

  • 在计算高度的时候, 已经计算了平衡的信息, 于是将 isBlanced 的先序改成后序, 并合在高度计算过程中。