传送到leetcode: leetcode-104

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// dfs实现
func maxDepth(root *TreeNode) int {
max := 0
startDeep := 0

var dfs func(node *TreeNode, startDeep int)
dfs = func(node *TreeNode, startDeep int) {
if node == nil {
return
}
startDeep = startDeep + 1

if node.Left == nil && node.Right == nil {
if startDeep > max {
max = startDeep
}
}

dfs(node.Left, startDeep)
dfs(node.Right, startDeep)
}

dfs(root, startDeep)
return max
}