|
1 | 1 | from typing import List, Optional |
2 | 2 |
|
3 | 3 |
|
| 4 | +class QuadTreeNode: |
| 5 | + """Quad tree node.""" |
| 6 | + |
| 7 | + def __init__( |
| 8 | + self, |
| 9 | + val: int = 0, |
| 10 | + isLeaf: bool = False, |
| 11 | + topLeft: Optional["QuadTreeNode"] = None, |
| 12 | + topRight: Optional["QuadTreeNode"] = None, |
| 13 | + bottomLeft: Optional["QuadTreeNode"] = None, |
| 14 | + bottomRight: Optional["QuadTreeNode"] = None, |
| 15 | + ): |
| 16 | + self.val = val |
| 17 | + self.isLeaf = isLeaf |
| 18 | + self.topLeft = topLeft |
| 19 | + self.topRight = topRight |
| 20 | + self.bottomLeft = bottomLeft |
| 21 | + self.bottomRight = bottomRight |
| 22 | + |
| 23 | + def __eq__(self, other: "QuadTreeNode") -> bool: |
| 24 | + if self is None and other is None: |
| 25 | + return True |
| 26 | + elif self is None: |
| 27 | + return False |
| 28 | + elif other is None: |
| 29 | + return False |
| 30 | + else: |
| 31 | + return ( |
| 32 | + self.val == other.val |
| 33 | + and self.isLeaf == other.isLeaf |
| 34 | + and self.topLeft == other.topLeft |
| 35 | + and self.topRight == other.topRight |
| 36 | + and self.bottomLeft == other.bottomLeft |
| 37 | + and self.bottomRight == other.bottomRight |
| 38 | + ) |
| 39 | + |
| 40 | + @staticmethod |
| 41 | + def build(levelorder: List[List[int]]) -> "QuadTreeNode": |
| 42 | + """Build a binary tree from levelorder traversal.""" |
| 43 | + if not levelorder: |
| 44 | + return None |
| 45 | + |
| 46 | + node_data = levelorder.pop(0) |
| 47 | + if node_data is None: |
| 48 | + return None |
| 49 | + |
| 50 | + isLeaf, val = node_data |
| 51 | + head = QuadTreeNode(val, isLeaf) |
| 52 | + queue = [(head, isLeaf)] |
| 53 | + |
| 54 | + while queue and levelorder: |
| 55 | + node, isLeaf = queue.pop(0) |
| 56 | + |
| 57 | + node_data = levelorder.pop(0) |
| 58 | + if node_data: |
| 59 | + isLeaf, val = node_data |
| 60 | + node.topLeft = QuadTreeNode(val, isLeaf) |
| 61 | + queue.append((node.topLeft, isLeaf)) |
| 62 | + |
| 63 | + node_data = levelorder.pop(0) |
| 64 | + if node_data: |
| 65 | + isLeaf, val = node_data |
| 66 | + node.topRight = QuadTreeNode(val, isLeaf) |
| 67 | + queue.append((node.topRight, isLeaf)) |
| 68 | + |
| 69 | + node_data = levelorder.pop(0) |
| 70 | + if node_data: |
| 71 | + isLeaf, val = node_data |
| 72 | + node.bottomLeft = QuadTreeNode(val, isLeaf) |
| 73 | + queue.append((node.bottomLeft, isLeaf)) |
| 74 | + |
| 75 | + node_data = levelorder.pop(0) |
| 76 | + if node_data: |
| 77 | + isLeaf, val = node_data |
| 78 | + node.bottomRight = QuadTreeNode(val, isLeaf) |
| 79 | + queue.append((node.bottomRight, isLeaf)) |
| 80 | + return head |
| 81 | + |
| 82 | + |
4 | 83 | class TreeNode: |
5 | 84 | """Binary tree node.""" |
6 | 85 |
|
|
0 commit comments