Question 1
Question: enter a binary search tree and convert it into a sorted two-way linked list.
You cannot create any new node, but you can only adjust the pointer. For more information, see July. Thank you.
Analysis:
As shown in the preceding example, we can see that the central Traversal method is used for tree traversal, and the forward and backward directions of nodes in the tree are modified in turn.
Because it is required that a new node cannot be created, because when you change the direction of the Central traversal, you need a pointer to the address of the node that was last traversed, so that
The point of the current pointer. Therefore, a pointer is required. (Isn't this a node creation ?)
Therefore, the program is mainly divided into two parts: one is the construction of the tree (the node insertion function), the other is the sequential traversal of the tree, and in the process of the sequential traversal, modify
The frontend and backend of the currently traversed node.
The Code is as follows:
[Cpp]
# Include <iostream>
# Include <stdio. h>
Using namespace std;
Typedef struct BSTreeNode
{
Float value;
BSTreeNode * NodeLeft;
BSTreeNode * NodeRight;
} DoubleList;
DoubleList * listHead;
DoubleList * listIndex;
Void convert2DoubleLIST (BSTreeNode * nodeCurrent );
Void InOrder (BSTreeNode * root)
{
If (NULL = root)
{
Return;
}
If (root-> NodeLeft! = NULL)
{
InOrder (root-> NodeLeft );
}
Convert2DoubleLIST (root );
If (NULL! = Root-> NodeRight)
{
InOrder (root-> NodeRight );
}
}
Void convert2DoubleLIST (BSTreeNode * nodeCurrent)
{
// ListIndex stores the last record
NodeCurrent-> NodeLeft = listIndex;
If (NULL = listIndex)
{
ListHead = nodeCurrent;
}
Else
// All operations are performed on the address.
{
// Last processed Node
ListIndex-> NodeRight = nodeCurrent;
}
ListIndex = nodeCurrent;
Cout <nodeCurrent-> value <endl;
}
Void addBSTreeNode (BSTreeNode * & root, float value ){
// Create a binary search tree
If (NULL = root) // This is because root = NULL is easy to write as root = NULL.
{
BSTreeNode * paddNode = new BSTreeNode ();
PaddNode-> value = value;
PaddNode-> NodeLeft = NULL;
PaddNode-> NodeRight = NULL;
Root = paddNode;
}
Else
{
If (value <root-> value)
{
AddBSTreeNode (root-> NodeLeft, value );
}
Else if (value> root-> value)
{
AddBSTreeNode (root-> NodeRight, value );
}
Else
{
Cout <"insert nodes repeatedly" <endl;
}
}
}
Int main (){
ListIndex = NULL;
BSTreeNode * root = NULL;
AddBSTreeNode (root, 10 );
AddBSTreeNode (root, 6 );
AddBSTreeNode (root, 4 );
AddBSTreeNode (root, 8 );
AddBSTreeNode (root, 12 );
AddBSTreeNode (root, 14 );
AddBSTreeNode (root, 16 );
AddBSTreeNode (root, 15 );
InOrder (root );
Return 0;
}