Morris Traversal is a way to traverse the tree without using stack and recursion.
Given a binary tree, traverse the tree in inorder fashion using constant space and linear time without recursion.
We need to use the parent pointer to traverse the tree.
- Get the the leftmost node of the root of the tree.
- Yield the node.
- Check if the node has a right child.
- If it has a right child, find the leftmost node of the right child.
- If it doesn't have a right child
- Go up the tree until you find a node that is not right child of its parent.
- Go to the parent of that node.
 
- Repeat from step 2 until the node is None.
- Time Complexity: O(n)
- Space Complexity: O(1)
You can see full working code for all examples (and more) here.
def iterative_inorder(root):
    cur = root
    # Navigate to the leftmost node
    while cur and cur.left:
        cur = cur.left
    while cur:
        yield cur.data
        # If right child exists, visit this subtree
        if cur.right:
            cur = cur.right
            while cur.left:
                cur = cur.left
        else:
            # Traverse back up to the parent
            while cur.parent and cur == cur.parent.right:
                cur = cur.parent
            cur = cur.parentvoid iterativeInorder(Node* root) {
    Node* cur = root;
    // Find the leftmost node
    while (cur && cur->left) {
        cur = cur->left;
    }
    while (cur) {
        std::cout << cur->data << " "; // Output the data
        // Traverse the right subtree
        if (cur->right) {
            cur = cur->right;
            while (cur->left) {
                cur = cur->left;
            }
        } else {
            // Move up the tree
            while (cur->parent && cur == cur->parent->right) {
                cur = cur->parent;
            }
            cur = cur->parent;
        }
    }
}Contributions are welcome! If you find a bug or want to contribute, feel free to create an issue or open a pull request!
I would personally thank anybody who can open a pull request to add more examples in other languages!
This project is licensed under the MIT License. See LICENSE for more details.
The algorithm was created and published by 1mpossible-code.