-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
47 lines (39 loc) · 818 Bytes
/
main.go
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package maximumdepthofbinarytree
import (
"LeetcodeGolang/structures"
"math"
)
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 時間複雜 O(n), 空間複雜 O(1)
func MaxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return int(math.Max(float64(MaxDepth(root.Left)), float64(MaxDepth(root.Right)))) + 1
}
// 時間複雜 O(n), 空間複雜 O(1)
func MaxDepthKimi(root *TreeNode) int {
count := 0
return depth(root, count)
}
func depth(root *TreeNode, count int) int {
if root != nil {
count++
countL := depth(root.Left, count)
countR := depth(root.Right, count)
if countL > countR {
count = countL
} else {
count = countR
}
}
return count
}