![]() |
VOOZH | about |
Given the root of a binary tree, Find its Preorder traversal using Morris Traversal, i.e., without using recursion or a stack.
Examples:
Input:
👁 Iterative-Postorder-TraversalOutput: [1, 2, 4, 5, 3]
Explanation: Preorder traversal (Root->Left->Right) of the tree is 1, 2, 4, 5, 3.Input:
👁 Iterative-Postorder-Traversal-2Output: [8, 1, 7, 10, 5, 10, 6, 6]
Explanation: Preorder traversal (Root->Left->Right) of the tree is 8, 1, 7, 10, 5, 10, 6, 6.
The key idea is to temporarily establish links to a node’s inorder predecessor so that we can traverse the tree and print the data in preorder. After visiting the nodes, we revert these links to restore the tree to its original structure. Although the tree is temporarily modified during traversal, it remains unchanged once the traversal is complete.
Morris Preorder Traversal Steps
Start with root Node(curr) and for each node:
1 2 4 5 3
Time Complexity: O(n)
Auxiliary Space: O(1)