题目链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/
难度:简单

描述:
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

题解

  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 isBalanced(self, root: TreeNode) -> bool:
  9. def recursion(root):
  10. if root is None:
  11. return 0
  12. left_depth = recursion(root.left)
  13. if left_depth == -1:
  14. return -1
  15. right_depth = recursion(root.right)
  16. if right_depth == -1:
  17. return -1
  18. if abs(left_depth - right_depth) < 2:
  19. return max(left_depth, right_depth) + 1
  20. else:
  21. return -1
  22. return recursion(root) != -1