![]() |
VOOZH | about |
Given an N-ary Tree. The task is to write a program to perform the preorder traversal of the given n-ary tree.
Examples:
Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 Output: 1 2 5 10 6 11 12 13 3 4 7 8 9 Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 Output: 1 2 5 6 3 4 7 8 9
The preorder Traversal of an N-ary Tree is similar to the preorder traversal of a Binary Search Tree or Binary Tree with the only difference that is, all the child nodes of a parent are traversed from left to right in a sequence.
Iterative Preorder Traversal of Binary Tree.
Cases to handle during traversal: Two Cases have been taken care of in this Iterative Preorder Traversal Algorithm:
Note: In the below python implementation, a "dequeue" is used to implement the stack instead of a list because of its efficient append and pop operations.
Below is the implementation of the above approach:
1 2 5 10 6 11 12 13 3 4 7 8 9
Complexity Analysis:
Using Recursion:
Approach:
Below is the implementation of the above algorithm:
1 2 5 10 6 11 12 13 3 4 7 8 9
Complexity Analysis:
Time Complexity: O(N), Where n is the total number of nodes in the given tree.
Auxiliary Space: O(h), Where h is the height of the given tree if you consider the Auxiliary stack space of the recursion.