![]() |
VOOZH | about |
Given an n-ary tree containing positive node values. The task is to print the preorder traversal without using recursion.
Note: An n-ary tree is a tree where each node can have zero or more children. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branches or children for each node.
Examples:
Input: root
1
/ | \
2 3 4
/ \ |
5 6 7Output: 1 2 5 6 3 7 4
Input: root
11
/ | \
21 29 90
/ / \ \
18 10 12 77Output: 11 21 18 29 10 12 90 77
The idea is to use a stack to simulate recursion and perform iterative preorder traversal. We start by pushing the root into the stack. Then, in each iteration, we pop the top node, process it by adding its data to the result, and push its children from right to left. This ensures the leftmost child is processed first, mimicking recursive preorder traversal. The process continues until the stack is empty, giving the final traversal order.
Steps to implement the above idea:
Below is the implementation of the above approach:
11 21 18 29 10 12 90 77
Time Complexity: O(n), as each node is processed once
Space Complexity: O(n), as in worst case when all nodes are in stack