|
1 | 1 | """
|
2 | 2 | Constraints:
|
3 |
| -- |
| 3 | +- The number of nodes in the root tree is in the range [1, 2000]. |
| 4 | +- The number of nodes in the subRoot tree is in the range [1, 1000]. |
| 5 | +- -10^4 <= root.val <= 10^4 |
| 6 | +- -10^4 <= subRoot.val <= 10^4 |
4 | 7 |
|
5 |
| -Time Complexity: |
6 |
| -- |
| 8 | +Time Complexity: O(m * n) |
| 9 | +- m: root์ ๋
ธ๋ ์ |
| 10 | +- n: subRoot์ ๋
ธ๋ ์ |
7 | 11 |
|
8 |
| -Space Complexity: |
9 |
| -- |
| 12 | +Space Complexity: O(m) |
| 13 | +- ์ฌ๊ท ํธ์ถ ์คํ์ ์ต๋ ๊น์ด = root์ ๋์ด(?) |
10 | 14 |
|
11 | 15 | ํ์ด๋ฐฉ๋ฒ:
|
12 |
| -1. |
| 16 | +1. Base case ์ฒ๋ฆฌ: |
| 17 | + - subRoot๊ฐ ์์ ๋ โ True |
| 18 | + - root๊ฐ ๋น ํธ๋ฆฌ์ด๊ณ , subRoot๊ฐ ์์ ๋ โ False |
| 19 | +2. ๊ฐ ๋
ธ๋๋ฅผ ๋น๊ตํ์ฌ ๋์ผํ ํธ๋ฆฌ์ธ์ง ํ๋จํ๋ ํจ์ ํ์ฉ: |
| 20 | + - isSameTree ํจ์: ๋ ํธ๋ฆฌ๊ฐ ๋์ผํ์ง ์ฒดํฌ |
| 21 | + - ํ์ฌ ๋
ธ๋๋ถํฐ ์์ํด์ ๊ฐ์์ง ํ์ธ |
| 22 | + - ๊ฐ์ง ์๋ค๋ฉด ์ฌ๊ท๋ฅผ ํ์ฉํ์ฌ ์ผ์ชฝ/์ค๋ฅธ์ชฝ ์์ ๊ฒ์ฌ |
| 23 | +3. ์ฌ๊ท๋ฅผ ํ์ฉํ์ฌ ๊ฐ ๋
ธ๋์์ ์๋ธํธ๋ฆฌ ๊ฒ์ฌ: |
| 24 | + - ํ์ฌ ๋
ธ๋๋ถํฐ ์์ํ๋ ์๋ธํธ๋ฆฌ๊ฐ subRoot์ ๊ฐ์์ง ํ์ธ |
| 25 | + - ์๋๋ฉด ์ผ์ชฝ/์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ์์ ๊ฒ์ฌ |
13 | 26 | """
|
| 27 | +# Definition for a binary tree node. |
| 28 | +# class TreeNode: |
| 29 | +# def __init__(self, val=0, left=None, right=None): |
| 30 | +# self.val = val |
| 31 | +# self.left = left |
| 32 | +# self.right = right |
| 33 | +class Solution: |
| 34 | + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: |
| 35 | + if not subRoot: |
| 36 | + return True |
| 37 | + |
| 38 | + if not root: |
| 39 | + return False |
| 40 | + |
| 41 | + if self.isSameTree(root, subRoot): |
| 42 | + return True |
| 43 | + |
| 44 | + return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) |
| 45 | + |
| 46 | + def isSameTree(self, p: TreeNode, q: TreeNode): |
| 47 | + if not p and not q: |
| 48 | + return True |
| 49 | + |
| 50 | + if not p or not q: |
| 51 | + return False |
| 52 | + |
| 53 | + if p.val != q.val: |
| 54 | + return False |
| 55 | + |
| 56 | + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) |
0 commit comments