❝
这是一道 「简单」 题
https://leetcode.cn/problems/maximum-depth-of-binary-tree/❞
题目
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:给定二叉树 ,
/**
* 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(a, b int) int {
if a > b {
return a
}
return b
}
复杂度分析
-
时间复杂度:, n为二叉树中的节点个数,每个节点计算一次,时间复杂度为,n个节点总计为 。 -
空间复杂度:, n为二叉树中的节点个数,空间复杂度为调用栈的深度,最多为n,即二叉树退化为链表的时候。
- End -
本篇文章来源于微信公众号: i余数
微信扫描下方的二维码阅读本文

Comments NOTHING