Skip to content

Commit 838598b

Browse files
committed
feat: add subtree of another tree solution
1 parent bff8540 commit 838598b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import Optional
2+
3+
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
11+
class Solution:
12+
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
13+
if not subRoot:
14+
return True
15+
if not root:
16+
return False
17+
18+
if self.isSameTree(root, subRoot):
19+
return True
20+
21+
has_subroot_in_left = self.isSubtree(root.left, subRoot)
22+
has_subroot_in_right = self.isSubtree(root.right, subRoot)
23+
24+
return has_subroot_in_left or has_subroot_in_right
25+
26+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
27+
"""
28+
- Idea: ๋‘ ํŠธ๋ฆฌ๋ฅผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋…ธ๋“œ ๋‹จ์œ„๋กœ ๋น„๊ตํ•œ๋‹ค.
29+
1. ๋‘ ๋…ธ๋“œ๊ฐ€ ๋ชจ๋‘ None์ด๋ผ๋ฉด ํ˜„์žฌ ๋‘ ํŠธ๋ฆฌ๋Š” ๋™์ผ
30+
2. ๋‘ ๋…ธ๋“œ๊ฐ€ None์ด ์•„๋‹ˆ๊ณ  ๊ฐ’์ด ๊ฐ™๋‹ค๋ฉด, ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ๋น„๊ต
31+
3. ๋‘ ๋…ธ๋“œ๊ฐ€ ๋‹ค๋ฅด๊ฑฐ๋‚˜ ํ•œ์ชฝ๋งŒ None์ด๋ฉด ๋‘ ํŠธ๋ฆฌ๋Š” ์ƒ์ด
32+
- Time Complexity: O(m). m์€ ๋” ์ž‘์€ ํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ์ˆ˜
33+
๊ฐ ๋…ธ๋“œ๋ฅผ ํ•œ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•˜๋ฏ€๋กœ O(m) ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฐ๋‹ค.
34+
- Space Complexity: O(h). h๋Š” ๋” ์ž‘์€ ํŠธ๋ฆฌ์˜ ๋†’์ด
35+
์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์— ์ตœ๋Œ€ h๋งŒํผ์˜ ๊ณต๊ฐ„์ด ์‚ฌ์šฉ๋œ๋‹ค.
36+
"""
37+
38+
if not p and not q:
39+
return True
40+
41+
if p and q and p.val == q.val:
42+
is_left_equal = self.isSameTree(p.left, q.left)
43+
is_right_equal = self.isSameTree(p.right, q.right)
44+
45+
return is_left_equal and is_right_equal
46+
47+
return False

0 commit comments

Comments
ย (0)