|
| 1 | +from collections import defaultdict |
| 2 | + |
| 3 | +class WaveletTree: |
| 4 | + def __init__(self): |
| 5 | + self.list = [] |
| 6 | + self.rank = [] |
| 7 | + self.left = None |
| 8 | + self.right = None |
| 9 | + |
| 10 | + def assign_ranks(self): |
| 11 | + if not self.list: |
| 12 | + return [] |
| 13 | + maxi = max(self.list) |
| 14 | + mini = min(self.list) |
| 15 | + mid = (maxi + mini) / 2 |
| 16 | + return [0 if item <= mid else 1 for item in self.list] |
| 17 | + |
| 18 | +def create_walvet_tree(_list): |
| 19 | + _root = WaveletTree() |
| 20 | + _root.list = _list |
| 21 | + if len(_list) <= 1: |
| 22 | + return _root |
| 23 | + |
| 24 | + _root.rank = _root.assign_ranks() |
| 25 | + |
| 26 | + right = [] |
| 27 | + left = [] |
| 28 | + |
| 29 | + for index in range(0, len(_root.rank)): |
| 30 | + if _root.rank[index] == 1: |
| 31 | + right.append(_root.list[index]) |
| 32 | + else: |
| 33 | + left.append(_root.list[index]) |
| 34 | + |
| 35 | + _root.left = create_walvet_tree(left) |
| 36 | + _root.right = create_walvet_tree(right) |
| 37 | + return _root |
| 38 | + |
| 39 | + |
| 40 | +def inorder(_root): |
| 41 | + if _root: |
| 42 | + print(_root.list, _root.rank, _root.left, _root.right) |
| 43 | + inorder(_root.left) |
| 44 | + inorder(_root.right) |
| 45 | + |
| 46 | + |
| 47 | +def level_order(_root): |
| 48 | + |
| 49 | + if not _root: |
| 50 | + print("Empty tree") |
| 51 | + return |
| 52 | + |
| 53 | + dicto = defaultdict(lambda : []) |
| 54 | + |
| 55 | + queue = [(_root, 0)] |
| 56 | + |
| 57 | + while queue: |
| 58 | + item, lvl = queue.pop(0) |
| 59 | + if item == 'X': |
| 60 | + continue |
| 61 | + dicto[lvl].append( |
| 62 | + "".join([str(item) for item in item.rank]) if item.rank else 'X' |
| 63 | + ) |
| 64 | + queue.append((item.left if item.left else 'X', lvl + 1)) |
| 65 | + queue.append((item.right if item.left else 'X', lvl + 1)) |
| 66 | + return dicto |
| 67 | + |
| 68 | + |
| 69 | +def rqq(ksmallest, left, right): |
| 70 | + |
| 71 | + pass |
| 72 | + |
| 73 | + |
| 74 | +print("Enter input list:") |
| 75 | +# input_list = list(set(map(int, input().split()))) |
| 76 | +input_list = [6 , 2, 0 ,7 , 9, 3, 1 , 8 , 5, 4] |
| 77 | +root = create_walvet_tree(input_list) |
| 78 | +inorder(root) |
| 79 | +dicto = level_order(root) |
| 80 | +print(dicto) |
| 81 | +# print("RQQ inputs:") |
| 82 | +# k, l, r = list(map(int, input().split())) |
| 83 | +# rqq(k, l, r) |
| 84 | + |
| 85 | + |
| 86 | + |
| 87 | + |
0 commit comments