|
| 1 | +# time complexity: O(n) |
| 2 | +# space complexity: O(n) |
| 3 | +# Definition for a binary tree node. |
| 4 | +from collections import deque |
| 5 | +from typing import Dict, Optional, Set |
| 6 | + |
| 7 | + |
| 8 | +class TreeNode: |
| 9 | + def __init__(self, val=0, left=None, right=None): |
| 10 | + self.val = val |
| 11 | + self.left = left |
| 12 | + self.right = right |
| 13 | + |
| 14 | + |
| 15 | +class Solution: |
| 16 | + def convertTreeToGraph(self, current: TreeNode, parent: int, treeMap: Dict[int, Set[int]]): |
| 17 | + if current is None: |
| 18 | + return |
| 19 | + if current.val not in treeMap: |
| 20 | + treeMap[current.val] = set() |
| 21 | + adjacentList = treeMap[current.val] |
| 22 | + if parent != 0: |
| 23 | + adjacentList.add(parent) |
| 24 | + if current.left: |
| 25 | + adjacentList.add(current.left.val) |
| 26 | + if current.right: |
| 27 | + adjacentList.add(current.right.val) |
| 28 | + self.convertTreeToGraph(current.left, current.val, treeMap) |
| 29 | + self.convertTreeToGraph(current.right, current.val, treeMap) |
| 30 | + |
| 31 | + def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: |
| 32 | + treeMap: Dict[int, Set[int]] = {} |
| 33 | + self.convertTreeToGraph(root, 0, treeMap) |
| 34 | + print(treeMap) |
| 35 | + |
| 36 | + queue = deque([start]) |
| 37 | + minute = 0 |
| 38 | + visited = {start} |
| 39 | + while queue: |
| 40 | + levelSize = len(queue) |
| 41 | + while levelSize > 0: |
| 42 | + current = queue.popleft() |
| 43 | + for num in treeMap[current]: |
| 44 | + if num not in visited: |
| 45 | + visited.add(num) |
| 46 | + queue.append(num) |
| 47 | + levelSize -= 1 |
| 48 | + minute += 1 |
| 49 | + return minute - 1 |
| 50 | + |
| 51 | + |
| 52 | +root = TreeNode(1) |
| 53 | +root.left = TreeNode(5) |
| 54 | +root.left.right = TreeNode(4) |
| 55 | +root.left.right.left = TreeNode(9) |
| 56 | +root.left.right.right = TreeNode(2) |
| 57 | +root.right = TreeNode(3) |
| 58 | +root.right.left = TreeNode(10) |
| 59 | +root.right.right = TreeNode(6) |
| 60 | + |
| 61 | +print(Solution().amountOfTime(root, 3)) |
0 commit comments