Problem Description:
Enter a binary search tree and now convert the two-fork search tree into a sorted doubly linked list. And in the process of conversion, you cannot create any new nodes, only the point of the node pointer in the tree can be adjusted to implement.
Analytical:
With binary tree sequence traversal, because the middle sequence traversal binary search tree is characterized by small to large access nodes. When traversing access to the root node, assuming that the left side of the root node has been processed, simply connect the root node to the pointer of the last visited node (the largest node in the left subtree). The last node pointer of the current linked list is then updated.
Recursive algorithm:
(1) Middle sequence traversal.
(2) the pointer to the left Dial hand node is adjusted to the pointer to the previous node in the list, and the pointer to the right child node is adjusted to the pointer to the next node in the list.
The code is as follows:
void Convertnode (binarytreenode* pnode,binarytreenode** plastnodeinlist)
{
if (Pnode ==null)
Return
Binarytreenode *pcurrent = Pnode;
// Middle Sequence traversal
if (pcurrent->m_pleft! = NULL)
Convertnode (Pcurrent->m_pleft, plastnodeinlist);
// The pointer to the left Dial hand node is adjusted to the pointer to the previous node in the list.
Pcurrent->m_pleft = *plastnodeinlist;
// the pointer to the right child node is adjusted to the pointer to the next node in the list
if (*plastnodeinlist! = NULL)
(*plastnodeinlist)->m_pright = pcurrent;
// update the last node pointer of the current list
*plastnodeinlist = pcurrent;
if (pcurrent->m_pright! = NULL)
Convertnode (pcurrent->m_pright,plastnodeinlist);
}
binarytreenode* Convert (binarytreenode* prootoftree)
{
Binarytreenode *plastnodeinlist = NULL;
Convertnode (Prootoftree, &plastnodeinlist);
//plastnodeinlist Point to the tail node of the doubly linked list, we need to return to the head node .
Binarytreenode *pheadoflist = plastnodeinlist;
while (pheadoflist! = NULL && Pheadoflist->m_pleft! = null)
Pheadoflist = pheadoflist->m_pleft;
return pheadoflist;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
9:2 Fork Search tree and two-way linked list (binary search tree to ordered doubly linked list)