平衡二叉树:二叉树中任意节点的左右子树的深度相差不超过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 treeDepth(self, root: TreeNode) -> bool:
    9. if root is None:
    10. return 0
    11. else:
    12. return max(self.treeDepth(root.left), self.treeDepth(root.right)) + 1

    image.png

    https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/solution/mian-shi-ti-55-ii-ping-heng-er-cha-shu-cong-di-zhi/

    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 recur(root):
    10. if not root:
    11. return 0
    12. left = recur(root.left)
    13. if left == -1:
    14. return -1
    15. right = recur(root.right)
    16. if right == -1:
    17. return -1
    18. return max(left, right) + 1 if abs(left - right) <= 1 else -1
    19. return recur(root) != -1