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

Description

Given a binary tree, find its maximum depth.

给定一棵二叉树,求其最大深度。

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

最大深度指从根节点到最远叶子节点的最长路径,所经过的节点的数量。

Note

A leaf is a node with no children.

叶子节点是没有子节点的节点。

Examples

Example 1

Given binary tree [3, 9, 20, null, null, 15, 7]

    3
   / 
  9  20
    /  
   15   7

return its depth = 3.

Solution

解答此题,首先要确定以下几种状况

  • 树本身不存在时(null),其深度为 0

  • 树只存在一个根节点时,其深度为 1

  • 对于二叉树来说,其深度为 ( ext{max}{左子树的深度, 右子树的深度})

然后就可以写出相应的代码了(经压缩可以写成单行 return)

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
import kotlin.math.max

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

对于不是二叉树的情况,解法类似。例如,如果存在以下树结构

data class TreeNode(`val`: Int) {
    val children: MutableList<TreeNode>
}

那么也只是由“遍历左右子树”变为“遍历所有的子树,找其深度的最大值”,其余不变。

原文地址:https://www.cnblogs.com/zhongju/p/13772667.html