LeetCode-104.二叉树的最大深度

题目描述

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回它的最大深度 3

题解

  1. 递归

    将树深问题拆解为当前树的左右子树的最大深度+1

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    func maxDepth(_ root: TreeNode?) -> Int {
    guard let root = root else {
    return 0
    }
    if root.left === nil && root.right === nil {
    return 1
    }
    return max(maxDepth(root.left), maxDepth(root.right)) + 1
    }

  2. 层序遍历

    一层一层遍历,每遍历一层,深度+1

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    func maxDepth(_ root: TreeNode?) -> Int {
    guard let root = root else {
    return 0
    }
    var depth = 0
    var queue = [root]
    while !queue.isEmpty {
    var count = queue.count
    while count > 0 {
    let cur = queue.removeFirst()
    if let left = cur.left {
    queue.append(left)
    }
    if let right = cur.right {
    queue.append(right)
    }
    count -= 1
    }
    depth += 1
    }

    return depth
    }