题目
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof
解题思路
- 通过递归,不断的判断进来的节点 root 是否为空,最终 return 的其深度
- 如果root空,那么就 retrun 0
- 否则就用递归其左右的分支,找打最深的深度加上头节点 (+1)
递归
–执行用时:4 ms --内存消耗:4.4 MB
/**
* 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
}
//这里Deep已经从1开始,所以结果不用+1
return Depth(root,1)
}
func Depth(root *TreeNode,deep int) int{
if root.Left==nil && root.Right==nil{
return deep
}
Left:=deep
Right:=deep
if root.Left!=nil{
Left=Depth(root.Left,Left+1)
}
if root.Right!=nil{
Right=Depth(root.Right,Right+1)
}
return max(Left,Right)
}
func max(a,b int)int{
if a>b{
return a
}
return b
}
简化写法
–执行用时:4 ms --内存消耗:4.4 MB
/**
* 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
}
Left:=maxDepth(root.Left)
Right:=maxDepth(root.Right)
return max(Left,Right)+1
}
func max(a,b int)int{
if a>b{
return a
}
return b
}
或者
func maxDepth(root *TreeNode) int {
if root==nil{
return 0
}
return int(math.Max(float64(maxDepth(root.Left)),float64(maxDepth(root.Right))))+1
}