Skip to content

Commit c589c48

Browse files
committed
feat: add subtree-of-another-tree sol
1 parent 395d826 commit c589c48

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,90 @@
11
"""
22
[๋ฌธ์ œํ’€์ด]
33
# Inputs
4+
root, subRoot
45
56
# Outputs
7+
subRoot์˜ ํŠธ๋ฆฌ๊ฐ€ root ํŠธ๋ฆฌ์˜ ์„œ๋ธŒ ํŠธ๋ฆฌ์ธ์ง€์— ๋Œ€ํ•œ ์—ฌ๋ถ€
68
79
# Constraints
10+
- The number of nodes in the root tree is in the range [1, 2000].
11+
- The number of nodes in the subRoot tree is in the range [1, 1000].
12+
- -10^4 <= root.val <= 10^4
13+
- -10^4 <= subRoot.val <= 10^4
814
915
# Ideas
16+
์ •ํ™•ํžˆ ๊ตฌ์กฐ๋ž‘ ๋…ธ๋“œ ๊ฐœ์ˆ˜๋„ ๊ฐ™์•„์•ผ ํ•จ
17+
-> subRoot์˜ root ๋…ธ๋“œ ์ฐพ์œผ๋ฉด, ํƒ์ƒ‰ ์‹œ์ž‘
18+
-> ํƒ์ƒ‰ ๋๋‚˜๊ณ  ๋‚˜์„œ์˜ node ์ˆ˜ ๋ฐ˜ํ™˜
19+
ํƒ์ƒ‰ ๋„์ค‘์— node.value ๋‹ค๋ฅด๋ฉด false ๋ฐ˜ํ™˜
1020
1121
[ํšŒ๊ณ ]
1222
1323
"""
24+
# 1์ฐจ ์ œ์ถœ ์ฝ”๋“œ
25+
# Definition for a binary tree node.
26+
# class TreeNode:
27+
# def __init__(self, val=0, left=None, right=None):
28+
# self.val = val
29+
# self.left = left
30+
# self.right = right
31+
class Solution:
32+
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
33+
34+
def compare(r, sr):
35+
print('start compare')
36+
if r is not None and sr.val is not None:
37+
if r.val != sr.val:
38+
print('not same, exit compare')
39+
return False
40+
41+
elif r.val == sr.val == None:
42+
print('same, exit compare')
43+
return True
44+
45+
else:
46+
print('continue compare')
47+
return compare(r.left, sr.left) or compare(r.right, sr.right)
48+
49+
return True
50+
51+
def dfs(cur):
52+
if cur.val != subRoot.val:
53+
print('going left in root')
54+
dfs(cur.left)
55+
56+
print('going right in root')
57+
dfs(cur.right)
58+
59+
else:
60+
print('begin compare')
61+
return compare(cur, subRoot)
62+
return
63+
64+
return dfs(root)
65+
66+
# gpt ์ˆ˜์ • ์ฝ”๋“œ
67+
68+
class Solution:
69+
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
70+
71+
def isSameTree(s, t):
72+
if not s and not t:
73+
return True
74+
if not s or not t:
75+
return False
76+
if s.val != t.val:
77+
return False
78+
return isSameTree(s.left, t.left) and isSameTree(s.right, t.right)
79+
80+
def dfs(node):
81+
if not node:
82+
return False
83+
if isSameTree(node, subRoot):
84+
return True
85+
# ์•„๋ž˜ ๋‘˜ ์ค‘ ํ•˜๋‚˜๋ผ๋„ True๋ฉด ์ฆ‰์‹œ return True
86+
return dfs(node.left) or dfs(node.right)
87+
88+
return dfs(root)
1489

1590

0 commit comments

Comments
ย (0)