Skip to content

Commit 359815b

Browse files
aQuaaQua
aQua
authored and
aQua
committed
111 ut pass
1 parent 3f932cf commit 359815b

File tree

3 files changed

+109
-0
lines changed

3 files changed

+109
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# [111. Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/)
2+
3+
## 题目
4+
Given a binary tree, find its minimum depth.
5+
6+
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
7+
8+
## 解题思路
9+
10+
见程序注释
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package Problem0111
2+
3+
import (
4+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
5+
)
6+
7+
type TreeNode = kit.TreeNode
8+
9+
func minDepth(root *TreeNode) int {
10+
if root == nil {
11+
return 0
12+
}
13+
14+
if root.Left == nil && root.Right == nil {
15+
return 1
16+
}
17+
18+
return max(2, cur(root))
19+
}
20+
21+
func cur(node *TreeNode) int {
22+
if node == nil {
23+
return 1
24+
}
25+
26+
return min(minDepth(node.Left), minDepth(node.Right)) +1
27+
}
28+
29+
func max(a, b int) int {
30+
if a > b {
31+
return a
32+
}
33+
return b
34+
}
35+
36+
func min(a, b int) int {
37+
if a < b {
38+
return a
39+
}
40+
return b
41+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package Problem0111
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func Test_Problem0111(t *testing.T) {
12+
ast := assert.New(t)
13+
14+
// tcs is testcase slice
15+
tcs := []struct {
16+
pre, in []int
17+
ans int
18+
}{
19+
20+
{
21+
[]int{1, 2},
22+
[]int{2, 1},
23+
2,
24+
},
25+
26+
{
27+
[]int{1},
28+
[]int{1},
29+
1,
30+
},
31+
32+
{
33+
[]int{},
34+
[]int{},
35+
0,
36+
},
37+
38+
{
39+
[]int{2, 1, 5, 4, 3, 6, 7},
40+
[]int{1, 2, 3, 4, 5, 6, 7},
41+
2,
42+
},
43+
44+
{
45+
[]int{4, 2, 1, 3, 6, 5, 7},
46+
[]int{1, 2, 3, 4, 5, 6, 7},
47+
3,
48+
},
49+
50+
// 可以多个 testcase
51+
}
52+
53+
for _, tc := range tcs {
54+
fmt.Printf("~~%v~~\n", tc)
55+
56+
ast.Equal(tc.ans, minDepth(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc)
57+
}
58+
}

0 commit comments

Comments
 (0)