And finally ...

Create a new file trees.py in your system. Open the terminal and go to folder that contains trees.py such that ls command (in Mac, Linux) or dir command (in Windows) should give the filename in list.

Write the following code in trees.py :

class Node:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Traversal:
    def preOrderTraversal(self, root):
        def fun(root, result):
            if not root:
                return

            result.append(root.val)
            fun(root.left, result)
            fun(root.right, result)
        
        result = []
        fun(root, result)

        return result

    def inOrderTraversal(self, root):
        def fun(root, result):
            if not root:
                return

            fun(root.left, result)
            result.append(root.val)
            fun(root.right, result)
        
        result = []
        fun(root, result)

        return result

    def postOrderTraversal(self, root):
        def fun(root, result):
            if not root:
                return

            fun(root.left, result)
            fun(root.right, result)
            result.append(root.val)
        
        result = []
        fun(root, result)

        return result

if __name__ == "__main__":
    # main function
    # create tree nodes
    a = Node(val=1)
    b = Node(val=2)
    c = Node(val=3, left=a, right=b)
    d = Node(val=6)
    e = Node(val=7)
    f = Node(val=5, left=d, right=e)
    g = Node(val=4, left=c, right=f)

    
    # call function of preOrderTraversal algorithm
    preOrderTraversalResult = Traversal().preOrderTraversal(g)
    print(preOrderTraversalResult)

    # call function of inOrderTraversal algorithm
    inOrderTraversalResult = Traversal().inOrderTraversal(g)
    print(inOrderTraversalResult)

    # call function of postOrderTraversal algorithm
    postOrderTraversalResult = Traversal().postOrderTraversal(g)
    print(postOrderTraversalResult)

Now run the file using the following command:

python trees.py

The result should look something like this:

[4, 3, 1, 2, 5, 6, 7]
[1, 3, 2, 4, 6, 5, 7]
[1, 2, 3, 6, 7, 5, 4]

If you get any issues while running this code/following the lab, comment below for solution.

Happy coding !!

Discussion

2

0