算法刷题:深度优先搜索

less than 1 minute read

Published:

以下题目均来自LeetCode。

题目1:面试题55 - II. 平衡二叉树

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

示例 1:

给定二叉树 [3,9,20,null,null,15,7]
    3
   / \
  9  20
    /  \
   15   7

Answer:

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        def recur(root):
            if not root: return 0
            left = recur(root.left)
            if left == -1: return -1
            right = recur(root.right)
            if right == -1: return -1
            return max(left, right) + 1 if abs(left - right) <= 1 else -1

        return recur(root) != -1

题目2:

Answer:

题目3:

Answer:

题目4:

Answer:

题目5:

Answer:

题目6:

Answer:

题目7:

Answer:

题目8:

Answer:

题目9:

Answer:

题目10:

Answer: