Tree - 104. Maximum Depth of Binary Tree

时间:2022-07-25
本文章向大家介绍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
}