Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 1863cc8

Browse filesBrowse files
Create LCR 143. 子结构判断.md
1 parent 90fe2d3 commit 1863cc8
Copy full SHA for 1863cc8

File tree

1 file changed

+63
-0
lines changed
Filter options

1 file changed

+63
-0
lines changed
+63Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#### LCR 143. 子结构判断
2+
3+
难度:中等
4+
5+
---
6+
7+
给定两棵二叉树 `tree1``tree2`,判断 `tree2` 是否以 `tree1` 的某个节点为根的子树具有 **相同的结构和节点值**
8+
注意, **空树**  不会是以 `tree1` 的某个节点为根的子树具有 **相同的结构和节点值**
9+
10+
**示例 1:**
11+
12+
![](https://pic.leetcode.cn/1694684670-vwyIgY-two_tree.png)
13+
14+
```
15+
输入:tree1 = [1,7,5], tree2 = [6,1]
16+
输出:false
17+
解释:tree2 与 tree1 的一个子树没有相同的结构和节点值。
18+
```
19+
20+
**示例 2:**
21+
22+
![](https://pic.leetcode.cn/1694685602-myWXCv-two_tree_2.png)
23+
24+
```
25+
输入:tree1 = [3,6,7,1,8], tree2 = [6,1]
26+
输出:true
27+
解释:tree2 与 tree1 的一个子树拥有相同的结构和节点值。即 6 - > 1。
28+
```
29+
30+
**提示:**
31+
32+
`0 <= 节点个数 <= 10000`
33+
34+
---
35+
36+
深度搜索优先:
37+
38+
```Go
39+
/**
40+
* Definition for a binary tree node.
41+
* type TreeNode struct {
42+
* Val int
43+
* Left *TreeNode
44+
* Right *TreeNode
45+
* }
46+
*/
47+
func isSubStructure(A *TreeNode, B *TreeNode) bool {
48+
if A == nil || B == nil {
49+
return false
50+
}
51+
return dfs(A, B) || isSubStructure(A.Left, B) || isSubStructure(A.Right, B)
52+
}
53+
54+
func dfs(A *TreeNode, B *TreeNode) bool {
55+
if B == nil {
56+
return true
57+
}
58+
if A == nil || A .Val != B.Val {
59+
return false
60+
}
61+
return dfs(A.Left, B.Left) && dfs(A.Right, B.Right)
62+
}
63+
```

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.