diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index dc36f3f4..b9a0aa68 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -63,3 +63,7 @@ 3. [N-th Term Of Fibonacci Series](dynamic_programming/fibonacci_series_nth_term.py) 4. [Catalan Sequence](dynamic_programming/catalan_sequence.py) 5. [0/1 Knapsack Problem](dynamic_programming/knapsack.py) + +## Trees + +1. [Binary Tree](trees/binary_tree.py) diff --git a/algorithms/Python/trees/binary_tree.py b/algorithms/Python/trees/binary_tree.py new file mode 100644 index 00000000..4fc4d46f --- /dev/null +++ b/algorithms/Python/trees/binary_tree.py @@ -0,0 +1,77 @@ +# Author: github.com/Mo-Shakib + +class Node: + def __init__(self, data = None): + self.left = None + self.right = None + self.data = data + + # for setting left node + def setLeft(self, node): + self.left = node + + # for setting right node + def setRight(self, node): + self.right = node + + # for getting the left node + def getLeft(self): + return self.left + + # for getting right node + def getRight(self): + return self.right + + # for setting data of a node + def setData(self, data): + self.data = data + + # for getting data of a node + def getData(self): + return self.data + + +# in this we traverse first to the leftmost node, then print its data and then traverse for rightmost node +def inorder(Tree): + if Tree: + inorder(Tree.getLeft()) + print(Tree.getData(), end = ' ') + inorder(Tree.getRight()) + return + +# in this we first print the root node and then traverse towards leftmost node and then to the rightmost node +def preorder(Tree): + if Tree: + print(Tree.getData(), end = ' ') + preorder(Tree.getLeft()) + preorder(Tree.getRight()) + return + +# in this we first traverse to the leftmost node and then to the rightmost node and then print the data +def postorder(Tree): + if Tree: + postorder(Tree.getLeft()) + postorder(Tree.getRight()) + print(Tree.getData(), end = ' ') + return + +if __name__ == '__main__': + root = Node(1) + root.setLeft(Node(2)) + root.setRight(Node(3)) + root.left.setLeft(Node(4)) + + print('Inorder Traversal:') + inorder(root) + print('\nPreorder Traversal:') + preorder(root) + print('\nPostorder Traversal:') + postorder(root) + + # OUTPUT: + # Inorder Traversal: + # 4 2 1 3 + # Preorder Traversal: + # 1 2 4 3 + # Postorder Traversal: + # 4 2 3 1