Print? # Include <iostream>
# Include <stack>
Using namespace std;
// Node
Struct node
{
Node * lchild, * rchild;
Int value;
};
// Binary Search Tree
Class list
{
Public:
List ();
Void InOrder_transfer ();
Private:
Node * root;
};
Void list: InOrder_transfer ()
{
// If the root node is empty, return
If (root = NULL)
Return;
// Use the stack method to solve the non-recursive sequential traversal Problem
Stack <node *> s;
Bool head = 0;
Node * curr = root;
Node * post = NULL;
While (1 ){
While (curr ){
S. push (curr );
Curr = curr-> lchild;
}
If (s. empty ())
Break;
Curr = s. top ();
S. pop ();
// You can see that the Left node points to the previous element, and the right node points to the next element.
Curr-> lchild = post;
If (post)
Post-> rchild = curr;
// The first node is a two-way linked list header node.
If (NULL = head ){
Head = 1;
Root = curr;
}
// The Position of the original central output Node
// Cout <curr-> value <"";
Post = curr;
Curr = curr-> rchild;
}
// Output two-way linked list Node
Curr = root;
While (curr ){
Cout <curr-> value <"";
Curr = curr-> rchild;
}
}
List: list ()
{
Cout <"Enter the node you want to enter and press '#' to exit:" <endl;
Int I;
// You can use cin. fail () and cin. bad () to determine whether or not
If (cin> I = NULL ){
Cout <"your input is incorrect" <endl;
Exit (-1 );
}
// Create the root node
Root = new node;
Root-> value = I;
Root-> lchild = NULL;
Root-> rchild = NULL;
// Create two temporary nodes, p open up new nodes, and q is binary search and positioning
Node * p, * q;
While (cin> I! = NULL ){
// Create a new node
P = new node;
P-> value = I;
P-> lchild = NULL;
P-> rchild = NULL;
// The binary search tree starts from q = root. If it is small, it turns to left, and if it is large, it turns to right. If it has a position, it is inserted.
Q = root;
While (1 ){
// The inserted node is smaller than the Compare value of the node. If the left node is empty, the inserted node is inserted. Otherwise, q = q-> lchild continues to judge.
If (p-> value <q-> value ){
If (q-> lchild)
Q = q-> lchild;
Else {
Q-> lchild = p;
Break;
}
}
// The inserted node is greater than the Compare value of the node. If the right node is empty, the inserted node is inserted. Otherwise, q = q-> rchild continues to judge.
Else if (p-> value> q-> value ){
If (q-> rchild)
Q = q-> rchild;
Else {
Q-> rchild = p;
Break;
}
}
// If the two nodes are equal, exit the program directly (somewhat violent)
Else {
Cout <"node repeated !! "<Endl;
Exit (-1 );
}
}
}
}
Void main ()
{
List test;
// Convert the binary sorting tree to a two-way linked list in the middle-order traversal.
Test. InOrder_transfer ();
System ("pause ");
}