Enter a binary search tree and convert it into a sorted two-way linked list. You must not create any new node. You only need to adjust the pointer point. For example, Binary Search Tree
10
/\
6 14
/\/\
4 8 12 16
Convert to a two-way linked list 4 = 6 = 8 = 10 = 12 = 14 = 16.
Analysis: You can use recursion to convert the left subtree into a bidirectional list, then the right subtree into a bidirectional list, and finally the two bidirectional lists and the root node groups are connected at the beginning and end, combine them into a bidirectional list.
The following is the implementationCode:
Bstreenode. h
View code
# PragmaOnce
# Include<Cstdlib>
Using NamespaceSTD;
ClassBstree;
Class Bstreenode
{
Friend Class Bstree;
Public :
Bstreenode ( Int Data, bstreenode * RC = Null, bstreenode * LC = Null );
Private :
Int Data;
Bstreenode * RC;
Bstreenode * LC;
};
Bstreenode. cpp
View code
#include " bstreenode. h "
bstreenode: bstreenode ( int data, bstreenode * RC, bstreenode * Lc)
{< br> This -> data = data;
This -> LC = lC;
This -> RC = RC;
}
Bstree. h
View code
# PragmaOnce
# Include"Bstreenode. h"
Class Bstree
{
Public :
Bstree ( Void );
~ Bstree ( Void );
Void Insert ( Int Data );
Void Converttodoublelist ();
Private :
Bstreenode * Root;
Void Del (bstreenode * Node );
Bstreenode * Converttodoublelist (bstreenode *& Node );
};
Bstree. cpp
View code
# Include"Bstree. h"
# Include<Cstdlib>
Using NamespaceSTD;
Bstree: bstree (Void)
{
Root=NULL;
}
Void Bstree: insert ( Int Data)
{
If (Root = Null)
{
Root = New Bstreenode (data );
}
Else
{
Bstreenode * Cur, * Pre;
Pre = NULL;
Cur = Root;
While ( True )
{
Pre = Cur;
If (Cur -> Data <= Data)
{
Cur = Cur -> RC;
If ( ! Cur)
{
Pre -> RC = New Bstreenode (data );
Break ;
}
}
Else
{
Cur = Cur -> LC;
If ( ! Cur)
{
Pre -> LC = New Bstreenode (data );
Break ;
}
}
}
}
}
Bstree ::~Bstree (Void)
{
}
VoidBstree: del (bstreenode*Node)
{
If(Node=Null)
Return;
Del (node->Lc );
Del (node->RC );
Delete node;
Root=NULL;
}
Bstreenode * Bstree: converttodoublelist (bstreenode *& Node)
{
If (Node = Null)
Return NULL;
Bstreenode * Lf, * LT, * RF, * RT, * F, * T;
Lf = Node -> LC;
RF = Node -> RC;
Lt = Converttodoublelist (LF );
RT = Converttodoublelist (RF );
If (LT ! = Null)
{
Lt -> RC = Node;
F = Lf;
}
Else
F = Node;
Node -> LC = Lt;
Node -> RC = RF;
If (RF ! = Null)
{
RF -> LC = Node;
T = RT;
}
Else
T = Node;
Node = F;
Return T;
}
VoidBstree: converttodoublelist ()
{
Converttodoublelist (Root );
}
Main. cpp
View code
# Include<Iostream>
# Include"Bstree. h"
Using NamespaceSTD;
IntMain ()
{
Bstree TR;
Tr. insert (10);
Tr. insert (7);
Tr. insert (8);
Tr. insert (52);
Tr. converttodoublelist ();
Return 0;
}