| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- tree
- GenerativeAI
- 슬라이딩윈도우
- stratascratch
- nlp
- heap
- Python3
- codeup
- sql코테
- 릿코드
- 코드업
- BFS
- 니트코드
- Stack
- graph
- SQL
- dfs
- 알고리즘
- 생성형AI
- GenAI
- 파이썬
- array
- 투포인터
- LeetCode
- Greedy
- two-pointer
- 파이썬알고리즘
- Python
- 리트코드
- binary Tree
Archives
- Today
- Total
Tech for good
[Leetcode/Tree, Binary Search Tree, DFS] 1305. All Elements in Two Binary Search Trees 본문
IT/Computer Science
[Leetcode/Tree, Binary Search Tree, DFS] 1305. All Elements in Two Binary Search Trees
Diana Kang 2025. 7. 26. 04:45
# 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 getAllElements(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> List[int]:
def helper(root):
if not root:
return []
return helper(root.left) + [root.val] + helper(root.right)
one = helper(root1) # [1, 4, 2]
two = helper(root2) # [0, 1, 3]
return sorted(one+two)
# 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 getAllElements(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> List[int]:
# binary search tree -> left < right (two-pointers)
def helper(root):
if not root:
return []
return helper(root.left) + [root.val] + helper(root.right)
one = helper(root1) # [1, 4, 2]
two = helper(root2) # [0, 1, 3]
res = []
i, j = 0,0
while i < len(one) and j <len(two):
if one[i] <= two[j]:
res.append(one[i])
i += 1
else:
res.append(two[j])
j += 1
if i < len(one):
return res + one[i:len(one)+1]
if j < len(two):
return res + two[j:len(two)+1]'IT > Computer Science' 카테고리의 다른 글
| [HackerRank] Inorder Traversal of Binary Tree (0) | 2025.08.04 |
|---|---|
| [Leetcode/Tree, Binary Tree, DFS] 572. Subtree of Another Tree (0) | 2025.07.26 |
| [Leetcode/Tree, Binary Tree, DFS] 110. Balanced Binary Tree (0) | 2025.07.25 |
| [Leetcode/Tree, DFS, Binary Tree] 543. Diameter of Binary Tree (0) | 2025.07.25 |
| [Leetcode/Tree, Binary Tree, Stack, DFS] 94. Binary Tree Inorder Traversal (1) | 2025.07.24 |