Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 47bedf6

Browse files
aQuaaQua
aQua
authored and
aQua
committed
104 accepted. 12ms > 9ms.
1 parent 0efa9cf commit 47bedf6

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
2+
3+
## 题目
4+
Given a binary tree, find its maximum depth.
5+
6+
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
7+
8+
## 解题思路
9+
10+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package Problem0104
2+
3+
import (
4+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
5+
)
6+
7+
type TreeNode = kit.TreeNode
8+
9+
func maxDepth(root *TreeNode) int {
10+
res := 0
11+
12+
var dfs func(*TreeNode, int)
13+
dfs = func(root *TreeNode, level int) {
14+
if root == nil {
15+
return
16+
}
17+
18+
// 出现了新的 level
19+
if res < level {
20+
res = level
21+
}
22+
23+
dfs(root.Left, level+1)
24+
dfs(root.Right, level+1)
25+
}
26+
27+
dfs(root, 1)
28+
29+
return res
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package Problem0104
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/aQuaYi/LeetCode-in-Golang/kit"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func Test_Problem0104(t *testing.T) {
13+
ast := assert.New(t)
14+
15+
// tcs is testcase slice
16+
tcs := []struct {
17+
pre, in []int
18+
ans int
19+
}{
20+
21+
{
22+
[]int{},
23+
[]int{},
24+
0,
25+
},
26+
27+
{
28+
[]int{3, 9, 20, 15, 7},
29+
[]int{9, 3, 15, 20, 7},
30+
3,
31+
},
32+
33+
// 可以多个 testcase
34+
}
35+
36+
for _, tc := range tcs {
37+
fmt.Printf("~~%v~~\n", tc)
38+
39+
ast.Equal(tc.ans, maxDepth(kit.PreIn2Tree(tc.pre, tc.in)), "输入:%v", tc)
40+
}
41+
}

0 commit comments

Comments
 (0)