|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | + |
| 4 | +class Node: |
| 5 | + def __init__(self, key: Optional[float]) -> None: |
| 6 | + self._left: Optional[Node] = None |
| 7 | + self._right: Optional[Node] = None |
| 8 | + self._value: Optional[float] = key |
| 9 | + |
| 10 | + def display(self) -> None: |
| 11 | + if self._left: |
| 12 | + self._left.display() |
| 13 | + print(self._value, end=' ') |
| 14 | + if self._right: |
| 15 | + self._right.display() |
| 16 | + |
| 17 | + def display_preorder(self) -> None: |
| 18 | + if self._value: |
| 19 | + print(self._value, end=' ') |
| 20 | + if self._left: |
| 21 | + self._left.display_preorder() |
| 22 | + if self._right: |
| 23 | + self._right.display_preorder() |
| 24 | + |
| 25 | + def display_inorder(self) -> None: |
| 26 | + if self._value: |
| 27 | + if self._left: |
| 28 | + self._left.display_inorder() |
| 29 | + print(self._value, end=' ') |
| 30 | + if self._right: |
| 31 | + self._right.display_inorder() |
| 32 | + |
| 33 | + def display_postorder(self) -> None: |
| 34 | + if self._value: |
| 35 | + if self._left: |
| 36 | + self._left.display_postorder() |
| 37 | + if self._right: |
| 38 | + self._right.display_postorder() |
| 39 | + print(self._value, end=' ') |
| 40 | + |
| 41 | + def insert(self, data: float) -> None: |
| 42 | + if self._value: |
| 43 | + if data < self._value: |
| 44 | + if self._left is None: |
| 45 | + self._left = Node(data) |
| 46 | + else: |
| 47 | + self._left.insert(data) |
| 48 | + elif data > self._value: |
| 49 | + if self._right is None: |
| 50 | + self._right = Node(data) |
| 51 | + else: |
| 52 | + self._right.insert(data) |
| 53 | + else: |
| 54 | + self._value = data |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == '__main__': |
| 58 | + root = Node(10) |
| 59 | + root._left = Node(12) |
| 60 | + root._right = Node(5) |
| 61 | + print("Without any order") |
| 62 | + root.display() |
| 63 | + print() |
| 64 | + root_1 = Node(None) |
| 65 | + root_1.insert(28) |
| 66 | + root_1.insert(4) |
| 67 | + root_1.insert(13) |
| 68 | + root_1.insert(130) |
| 69 | + root_1.insert(123) |
| 70 | + print("Now ordering with insert") |
| 71 | + root_1.display() |
| 72 | + print() |
| 73 | + print("Pre order") |
| 74 | + root_1.display_preorder() |
| 75 | + print() |
| 76 | + print("In Order") |
| 77 | + root_1.display_inorder() |
| 78 | + print() |
| 79 | + print("Post Order") |
| 80 | + root_1.display_postorder() |
| 81 | + print() |
0 commit comments