文章 224
评论 6
浏览 200766
Tree - 104. Maximum Depth of Binary Tree

Tree - 104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree

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.

Example:

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

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

思路:

一棵空树的深度为零,也就是可以看做叶子节点的孩子节点的深度为零,叶子节点的深度为1,而一个树的深度和高度相同,所以求一个树的深度其实就是左右子树的深度的最大值加一。递归求解就可以。

代码:

go:

/**

 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    if root == nil { return 0 }
    return max(maxDepth(root.Left), maxDepth(root.Right)) + 1
}

func max(i, j int) int {
    if i > j {
        return i
    }
    return j
}

标题:Tree - 104. Maximum Depth of Binary Tree
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/08/20/1566306777463.html

Nothing just happens, it's all part of a plan.

取消