|
1 | 1 | """
|
2 | 2 | [๋ฌธ์ ํ์ด]
|
3 | 3 | # Inputs
|
| 4 | +root, subRoot |
4 | 5 |
|
5 | 6 | # Outputs
|
| 7 | +subRoot์ ํธ๋ฆฌ๊ฐ root ํธ๋ฆฌ์ ์๋ธ ํธ๋ฆฌ์ธ์ง์ ๋ํ ์ฌ๋ถ |
6 | 8 |
|
7 | 9 | # 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 |
8 | 14 |
|
9 | 15 | # Ideas
|
| 16 | +์ ํํ ๊ตฌ์กฐ๋ ๋
ธ๋ ๊ฐ์๋ ๊ฐ์์ผ ํจ |
| 17 | +-> subRoot์ root ๋
ธ๋ ์ฐพ์ผ๋ฉด, ํ์ ์์ |
| 18 | +-> ํ์ ๋๋๊ณ ๋์์ node ์ ๋ฐํ |
| 19 | +ํ์ ๋์ค์ node.value ๋ค๋ฅด๋ฉด false ๋ฐํ |
10 | 20 |
|
11 | 21 | [ํ๊ณ ]
|
12 | 22 |
|
13 | 23 | """
|
| 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) |
14 | 89 |
|
15 | 90 |
|
0 commit comments