This repository was archived by the owner on Dec 19, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +69
-0
lines changed Expand file tree Collapse file tree 2 files changed +69
-0
lines changed Original file line number Diff line number Diff line change 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.**
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments