I’m working on a project where I need to implement different types of tree traversals (in-order, pre-order, post-order) for a binary tree. I understand the basic structure of a binary tree, but I’m struggling with how to write the recursive functions for each traversal method.
Here’s the basic structure of my binary tree:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
I’ve looked at some online resources, but I’m still confused about how the recursive calls work and how they ensure the correct order.
2
I suggest you to search the web
You can find solution in websites like geeksforgeeks
Here is an example
https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
I highly recommend her DEEPTI TALESRA https://youtu.be/RJhh3Jcc9zw?si=Xw4tfPxIIdz8S921
. She explains so well and goes through examples step by step