Problem Description:
Enter a two-dollar lookup tree to convert the two-dollar lookup tree into a sorted doubly linked list. Requires that no new nodes be created, only the pointer is adjusted.
10
/ /
6 14
/ / / /
4 8 12 16
Convert to doubly linked list
4=6=8=10=12=14=16.
Idea: Using recursive thought to solve, adjust the left and right sub-tree of a node, adjust the left pointer of the node to the Zuozi's maximum node, and then point to the smallest node of the right sub-tree.
The code is as follows:
Bstreenode * Convert (bstreenode *node)
{
if (node = = null)
return null;
Bstreenode *leftmax,*rightmin;
Leftmax = node->left;
Rightmin = node->right;
Find the maximum node of Zuozi while
(Leftmax! = NULL && leftmax->right! = null)
Leftmax = leftmax->right;
Find the smallest node of the right subtree while
(rightmin! = NULL && Rightmin->left! = null)
rightmin = rightmin->left;
Recursive solution to
Convert (node->right);
Convert (node->left);
Connect the same root node of the left and right subtree, but only with the sibling relationship
if (leftmax! = NULL)
leftmax->right = node;
if (rightmin! = NULL)
rightmin->left = node;
Node->left = Leftmax;
Node->right = rightmin;
return node;
}
In the test, we need to build a two-fork search tree, and the code to build and traverse the binary tree is given below.
struct Bstreenode
{
int value;
Bstreenode *left;
Bstreenode *right;
};
Bstreenode * Insert (bstreenode *p, int x)
{
if (p = = NULL)
{
p = new Bstreenode;
P->value = x;
P->left = NULL;
P->right = NULL;
}
else
{
if (P->value > x)
p->left = Insert (p->left, x);
if (P->value < x)
p->right = Insert (p->right, x);
}
return p;
}
void Traverse (Bstreenode *p)//middle order traversal
{
if (p = = NULL)
return;
Traverse (p->left);
cout<<p->value<< ";
Traverse (p->right);
}
I enjoy the copyright of the blog post, please indicate the source http://blog.csdn.net/wuzhekai1985