일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Class
- Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- 315. Count of Smaller Numbers After Self
- iterator
- 운영체제
- 프로그래머스
- 시바견
- 밴픽
- kaggle
- Python Code
- 715. Range Module
- Decorator
- DWG
- Python Implementation
- Python
- concurrency
- 43. Multiply Strings
- shiba
- t1
- Generator
- 파이썬
- 109. Convert Sorted List to Binary Search Tree
- LeetCode
- data science
- 컴퓨터의 구조
- Convert Sorted List to Binary Search Tree
- Regular Expression
- attribute
- Protocol
Archives
- Today
- Total
Scribbling
LeetCode: 652. Find Duplicate Subtrees 본문
All we have to do is traversing every node by dfs and checking whether current node's structure is already seen or not.
Then, we need to come up with a way to 'represent' a tree's structure. Here, we use a string to represent the tree structure. --> str(node.val) + (left tree structure) + (right tree structure)
If it is a new string, we add to our dictionary (self.dp).
If it is a already seen string, we check if it is seen for the second time with its value (self.dp[string]).
Time complexity: O(N)
Space Complexity: O(N)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
self.dp = {}
self.ret = []
self.dfs(root)
return self.ret
def dfs(self, node):
if not node:
return ""
left, right = self.dfs(node.left), self.dfs(node.right)
ret = str(node.val) + '(' + left + ')' + '(' + right + ')'
if ret not in self.dp:
self.dp[ret] = True
else:
if self.dp[ret]:
self.ret.append(node)
self.dp[ret] = False
return ret
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 1048. Longest String Chain (0) | 2022.02.27 |
---|---|
LeetCode: 990. Satisfiability of Equality Equations (0) | 2022.02.26 |
LeetCode: 465. Optimal Account Balancing (0) | 2022.02.17 |
LeetCode: 410. Split Array Largest Sum (0) | 2022.02.17 |
LeetCode: 315. Count of Smaller Numbers After Self (0) | 2022.02.10 |