Loading

LeetCode104.二叉树的最大深度

题目

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

3
/
9 20
/
15 7
返回它的最大深度 3 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题方法

深度优先(递归)

时间复杂度:O(n)空间复杂度:O(height)height为二叉树高度

广度优先(队列)

时间复杂度:O(n)空间复杂度:O(n)空间消耗为队列存储元素数量

代码

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
}

// 广度优先
func maxDepth2(root TreeNode) int {
if root == nil{
return 0
}
var result int
// 队列存储节点
queue := []
TreeNode{}
// 初始化添加根节点
queue = append(queue,root)
for len(queue) > 0{
ans := len(queue)
// 节点出队列,添加左右子节点入队列
for ans > 0{
node := queue[0]
queue = queue[1:]
if node.Left != nil{
queue = append(queue,node.Left)
}
if node.Right != nil{
queue = append(queue,node.Right)
}
ans--
}
// 一层所有节点出队列以后,深度++
result++
}
return result
}

posted @ 2021-09-06 14:36  励码万言  阅读(60)  评论(0)    收藏  举报