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

Commit 9791a50

Browse files
aQuaaQua
aQua
authored and
aQua
committed
572 added
1 parent 5a03f2a commit 9791a50

File tree

3 files changed

+117
-0
lines changed

3 files changed

+117
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# [572. Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
2+
3+
## 题目
4+
5+
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
6+
7+
Example 1:
8+
9+
```text
10+
Given tree s:
11+
3
12+
/ \
13+
4 5
14+
/ \
15+
1 2
16+
17+
Given tree t:
18+
4
19+
/ \
20+
1 2
21+
22+
Return true, because t has the same structure and node values with a subtree of s.
23+
```
24+
25+
Example 2:
26+
27+
```text
28+
Given tree s:
29+
3
30+
/ \
31+
4 5
32+
/ \
33+
1 2
34+
/
35+
0
36+
37+
Given tree t:
38+
4
39+
/ \
40+
1 2
41+
42+
Return false.
43+
```
44+
45+
## 解题思路
46+
47+
见程序注释
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package Problem0572
2+
3+
import (
4+
"github.com/aQuaYi/LeetCode-in-Go/kit"
5+
)
6+
7+
type TreeNode = kit.TreeNode
8+
9+
func isSubtree(s *TreeNode, t *TreeNode) bool {
10+
res := false
11+
12+
return res
13+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package Problem0572
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/aQuaYi/LeetCode-in-Go/kit"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
// tcs is testcase slice
13+
var tcs = []struct {
14+
spre, sin []int
15+
tpre, tin []int
16+
ans bool
17+
}{
18+
19+
{
20+
[]int{3, 4, 1, 2, 0, 5},
21+
[]int{1, 4, 0, 2, 3, 5},
22+
[]int{4, 1, 2},
23+
[]int{1, 4, 2},
24+
false,
25+
},
26+
27+
{
28+
[]int{3, 4, 1, 2, 5},
29+
[]int{1, 4, 2, 3, 5},
30+
[]int{4, 1, 2},
31+
[]int{1, 4, 2},
32+
true,
33+
},
34+
35+
// 可以有多个 testcase
36+
}
37+
38+
func Test_isSubtree(t *testing.T) {
39+
ast := assert.New(t)
40+
41+
for _, tc := range tcs {
42+
fmt.Printf("~~%v~~\n", tc)
43+
s := kit.PreIn2Tree(tc.spre, tc.sin)
44+
t := kit.PreIn2Tree(tc.tpre, tc.tin)
45+
ast.Equal(tc.ans, isSubtree(s, t), "输入:%v", tc)
46+
}
47+
}
48+
49+
func Benchmark_isSubtree(b *testing.B) {
50+
for i := 0; i < b.N; i++ {
51+
for _, tc := range tcs {
52+
s := kit.PreIn2Tree(tc.spre, tc.sin)
53+
t := kit.PreIn2Tree(tc.tpre, tc.tin)
54+
isSubtree(s, t)
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)