LeetCode 104. Maximum Depth of Binary Tree(二叉树的最大深度)

162 阅读1分钟

leetcode.com/problems/ma…

Discuss:www.cnblogs.com/grandyang/p…

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Example 3:

Input: root = []
Output: 0

Example 4:

Input: root = [0]
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -100 <= Node.val <= 100

解法一:

DFS,深度优先搜索。求二叉树的最大深度问题用到深度优先搜索 Depth First Search,递归的完美应用。

class Solution {
    fun maxDepth(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }
        return 1 + maxDepth(root.left).coerceAtLeast(maxDepth(root.right))
    }
}

解法二:

BFS,我们也可以使用层序遍历二叉树,然后计数总层数,即为二叉树的最大深度,参见代码如下:

class Solution {
    fun maxDepth(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }
        var result = 0
        val queue = ArrayDeque<TreeNode>()
        queue.offer(root)

        while (queue.isNotEmpty()) {
            val length = queue.size
            result++
            for (index in 0 until length) {
                val currentNode = queue.poll()
                currentNode.left?.let {
                    queue.offer(it)
                }
                currentNode.right?.let {
                    queue.offer(it)
                }
            }
        }
        return result
    }
}