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

Sign up
Appearance settings
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit 4a185e3

Browse files
committed
Add problem 572
1 parent a5d0180 commit 4a185e3

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

‎algorithms/572/README.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
## 572. Subtree of Another Tree
2+
3+
Given two **non-empty** binary trees **s** and **t**, check whether tree **t** has exactly
4+
the same structure and node values with a subtree of **s**. A subtree of **s** is a tree
5+
consists of a node in **s** and all of this node's descendants. The tree s could also be
6+
considered as a subtree of itself.
7+
8+
**Example 1:**
9+
10+
Given tree s:
11+
```
12+
3
13+
/ \
14+
4 5
15+
/ \
16+
1 2
17+
```
18+
19+
Given tree t:
20+
```
21+
4
22+
/ \
23+
1 2
24+
```
25+
Return **true**, because t has the same structure and node values with a subtree of s.
26+
27+
<br>
28+
29+
**Example 2:**
30+
Given tree s:
31+
```
32+
3
33+
/ \
34+
4 5
35+
/ \
36+
1 2
37+
/
38+
0
39+
```
40+
41+
Given tree t:
42+
```
43+
4
44+
/ \
45+
1 2
46+
```
47+
Return **false.**

‎algorithms/572/solution.go‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package main
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* type TreeNode struct {
6+
* Val int
7+
* Left *TreeNode
8+
* Right *TreeNode
9+
* }
10+
*/
11+
12+
func isSame(s *TreeNode, t *TreeNode) bool {
13+
return s == nil && t == nil ||
14+
s != nil && t != nil && s.Val == t.Val &&
15+
isSame(s.Left, t.Left) && isSame(s.Right, t.Right)
16+
}
17+
18+
// Time and space complexity: O(n) where n is size of the bigger tree
19+
func isSubtree(s *TreeNode, t *TreeNode) bool {
20+
return s != nil &&
21+
(isSame(s, t) || isSubtree(s.Left, t) || isSubtree(s.Right, t))
22+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /