Skip to content

Commit

Permalink
Merge pull request #927 from firepunch/week7
Browse files Browse the repository at this point in the history
[Mirim] Week7
  • Loading branch information
jka236 authored Mar 18, 2024
2 parents 8cce4d7 + 281a881 commit e32f775
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
17 changes: 17 additions & 0 deletions mirim/2024-03-17-buildTree-105.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
# 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 buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if inorder:
index = inorder.index(preorder.pop(0))
root = TreeNode(inorder[index])
root.left = self.buildTree(preorder, inorder[:index])
root.right = self.buildTree(preorder, inorder[index + 1 :])
return root
18 changes: 18 additions & 0 deletions mirim/2024-03-17-buildTree-106.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
# 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 buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not inorder or not postorder:
return None
root = TreeNode(postorder[-1])
index = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:index], postorder[:index])
root.right = self.buildTree(inorder[index + 1 :], postorder[index:-1])
return root
44 changes: 44 additions & 0 deletions mirim/2024-03-17-distanceK.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None


class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
res = []
if k == 0:
res = [target.val]
return res

graph = collections.defaultdict(list)
q = collections.deque([root])
while q:
node = q.popleft()
if node.left:
graph[node].append(node.left)
graph[node.left].append(node)
q.append(node.left)
if node.right:
graph[node].append(node.right)
graph[node.right].append(node)
q.append(node.right)

visited = set([target])
q = collections.deque([target])
level = 0
while q:
for i in range(len(q)):
node = q.popleft()
if level == k:
res.append(node.val)
else:
for edge in graph[node]:
if edge not in visited:
visited.add(edge)
q.append(edge)
level += 1
return res

0 comments on commit e32f775

Please sign in to comment.