Q:

Iterative Threaded Binary Tree Traversing with only constant extra space

How to traverse a threaded binary tree non recursively in O(n) without using a stack (just allowed to use constant extra space for temp variables, so we can't add visit flag to each node in the tree). I spent a good time thinking about it but it just doesn't seem to me to be doable unless we are going to traverse the memory locations that have the tree data. Let's say that we are using multiple array representation to implement pointers, then we can traverse the tree in O(n), does anyone have something else in mind?
Note This is not homework, just to save the energy of some keyboard strokes to write comments about homework!

A:

Let's say that we have the following threaded tree representation in C:
typedef struct threaded_binary_tree {
    int value;

    // Flag that tells whether right points to a right child or to a next
    // node in inorder.
    bool right_is_child;

    struct threaded_binary_tree *left, *right;
} threaded_binary_tree;

Then, traversing it in O(1) memory may look like this:
void inorder(threaded_binary_tree *node)
{
    threaded_binary_tree *prev = NULL;

    // Ignore empty trees
    if (node == NULL)
        return;

    // First, go to the leftmost leaf of the tree
    while (node->left != NULL)
        node = node->left;

    while (node != NULL) {
        // Nodes are visited along going upward in the tree
        printf("%d\n", node->value);

        prev = node;
        node = node->right;

        if (prev->right_is_child) {
            // We're descending into tree

            if (node != NULL) {
                // Again, go to the leftmost leaf in this subtree
                while (node->left != NULL)
                    node = node->left;
            }
        }
        // else, we're climbing up in the tree
    }
}

Warning: I haven't run this code.

