Created
October 17, 2021 11:05
-
-
Save darotar/edfce95e464b58f28bde5c895b41571c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
class Node: | |
def __init__(self, data): | |
self.left: Optional[Node] = None | |
self.right: Optional[Node] = None | |
self.data = data | |
def printTree(self): | |
if self.left: | |
self.left.printTree() | |
print(self.data) | |
if self.right: | |
self.right.printTree() | |
def insert(self, data): | |
if self.data: | |
if data < self.data: | |
if self.left is None: | |
self.left = Node(data) | |
else: | |
self.left.insert(data) | |
elif data > self.data: | |
if self.right is None: | |
self.right = Node(data) | |
else: | |
self.right.insert(data) | |
else: | |
self.data = data | |
def inorderTraversal(self, sub_root): | |
res = [] | |
if sub_root: | |
res = self.inorderTraversal(sub_root.left) | |
res.append(sub_root.data) | |
res = res + self.inorderTraversal(sub_root.right) | |
return res | |
def preorderTraversal(self, sub_root): | |
res = [] | |
if sub_root: | |
res.append(sub_root.data) | |
res = res + self.preorderTraversal(sub_root.left) | |
res = res + self.preorderTraversal(sub_root.right) | |
return res | |
def postorderTraversal(self, sub_root): | |
res = [] | |
if sub_root: | |
res = self.postorderTraversal(sub_root.left) | |
res = res + self.postorderTraversal(sub_root.right) | |
res.append(sub_root.data) | |
return res | |
# Press the green button in the gutter to run the script. | |
if __name__ == '__main__': | |
root = Node(27) | |
root.insert(14) | |
root.insert(35) | |
root.insert(10) | |
root.insert(19) | |
root.insert(31) | |
root.insert(42) | |
print(root.inorderTraversal(root)) | |
print(root.preorderTraversal(root)) | |
print(root.postorderTraversal(root)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment