-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path104-MaximumDepthOfBinaryTree.go
More file actions
110 lines (97 loc) · 2.41 KB
/
104-MaximumDepthOfBinaryTree.go
File metadata and controls
110 lines (97 loc) · 2.41 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
// 104. Maximum Depth of Binary Tree
// Given the root of a binary tree, return its maximum depth.
// A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
// Example 1:
// <img src="https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg" />
// Input: root = [3,9,20,null,null,15,7]
// Output: 3
// Example 2:
// Input: root = [1,null,2]
// Output: 2
// Constraints:
// The number of nodes in the tree is in the range [0, 10^4].
// -100 <= Node.val <= 100
import "fmt"
// Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// dfs
func maxDepth(root *TreeNode) int {
res := 0
var dfs func (node *TreeNode, count int)
dfs = func (node *TreeNode, count int) {
if node != nil {
dfs(node.Left, count+1)
dfs(node.Right, count+1)
}
if count > res {
res = count
}
}
dfs(root, res)
return res
}
// bfs
func maxDepth1(root *TreeNode) int {
if root == nil {
return 0
}
nodeList := []*TreeNode{root}
res := 0
for len(nodeList) > 0 {
for _, node := range nodeList {
nodeList = nodeList[1:]
if node.Left != nil {
nodeList = append(nodeList, node.Left)
}
if node.Right != nil {
nodeList = append(nodeList, node.Right)
}
}
res++
}
return res
}
// 递归
func maxDepth2(root *TreeNode) int {
if root == nil {
return 0
}
l, r := maxDepth2(root.Left) + 1, maxDepth2(root.Right) + 1
max := func (a int, b int) int { if a > b { return a; }; return b; }
return max(l,r)
}
func main() {
tree1 := &TreeNode {
3,
&TreeNode { 9, nil, nil },
&TreeNode {
20,
&TreeNode{15, nil, nil},
&TreeNode{7, nil, nil},
},
}
fmt.Println(maxDepth(tree1)) // 3
tree2 := &TreeNode {
1,
nil,
&TreeNode{2, nil, nil},
}
fmt.Println(maxDepth(tree2)) // 2
fmt.Println(maxDepth1(tree1)) // 3
fmt.Println(maxDepth1(tree2)) // 2
fmt.Println(maxDepth2(tree1)) // 3
fmt.Println(maxDepth2(tree2)) // 2
}