Occasionally see such a problem:
There is a binary tree, each node in addition to the left and right pointers, there is a pointer to the parent node.
Requires no recursion, and the middle sequence traverses the tree. Another requirement for space complexity is O (1).
The space complexity is O (1), the pendulum is not allowed to use the stack simulation recursive, so think about thinking, also consulted several friends, we all have the basic idea is similar, because there are pointers to the parent node, it is necessary to backtrack, so that you can not need the stack to do the record.
But realized, but found that a lot of detail needs to be perfected, such as traversal of the termination conditions, now I use a pre-traversal to the last right subtree, with this pointer as the termination condition.
Yesterday the general realization of a bit.
Post it and expect the talent to improve.
/* Idea: About the termination condition: the middle sequence traversal terminates at the last rchild, can only go through once, the node as the termination condition. Set a state (0,1,2) 0 for the CUR node at the time of the traversal to identify its left, right node condition has not yet been processed 1 to identify its left node being processed (including the absence of the left node) 2 The identity is returned from the right node (including cases where the right node does not exist) 3 states of Judgment (post->parent- >lchild = = Post) Such a method of judging. */void Inorder_norecursive (Linktree *root) {Linktree * cur=root, * post, *fin; int cur_state = 0; while (cur! = NULL)//check Find termination condition {post = cur; cur = cur->rchild;} fin = post; cur = root; Post = NULL; printf ("Fin Data:%d/n", fin->data); while (!) ( Cur = = Fin && cur_state >=1) {while (cur! = NULL && Cur->lchild! = NULL && cur_state! = 2) Search: Each traversal, the current state zeroing out, find the point that can be printed, return from the right node should not continue to traverse {cur_state = 0; cur = cur->lchild;} if (cur = = NULL && cur_state = = 1) | | Cur_state = = 2)//return: The right node is empty, the returned condition or the right node returns {cur = post; if (Cur->parent->lchild = = cur) cur_state = 1; else if (cur-> ;p Arent->rchild = = cur) cur_state = 2; Cur = cur->parent; } if (Cur->lchild = = NULL && Cur_state = = 0) cur_state = 1; Post = cur; The post is returned for CUR traversal to NULL, recording the active node if (Cur_state = = 1)//middle order Print {printf ("%d", cur->data); if (cur = = fin)//print the last one, explicitly exit break; The else if (cur_state = = 2)//Node 2 child nodes have been processed, returning continue; if (Cur->rchild = = fin)//If it is the parent node of the Fin node, set the Cur_state state in advance to prevent while exiting cur_state = 0; Cur = cur->rchild; } }
For general non-recursive formulations of the middle order, you can refer to here:
Http://blog.csdn.net/fuzhufang/archive/2009/03/08/3969375.aspx