Convert a binary search tree into a sorted two-way linked list

Source: Internet
Author: User

[Cpp]
<Span style = "color: rgb (51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px; "> <strong> converts a binary search tree into a sorted two-way linked list
</Strong> question:
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.

10
//
6 14
////
4 8 12 16

Convert to a two-way linked list
4 = 6 = 8 = 10 = 12 = 14 = 16. </Span>
[Cpp]
# Include <iostream>
Using namespace std;
 
Class Node {
Public:
Int data;
Node * left;
Node * right;

Node (int d = 0, Node * lr = 0, Node * rr = 0): data (d), left (lr), right (rr ){}
};
 
Node * create ()
{
Node * root;
Node * p4 = new Node (4 );
Node * p8 = new Node (8 );
Node * p6 = new Node (6, p4, p8 );

Node * p12 = new Node (12 );
Node * p16 = new Node (16 );
Node * p14 = new Node (14, p12, p16 );
 
Node * p11 = new Node (11 );
Node * p13 = new Node (13 );
P12-> left = p11;
P12-> right = p13;
 
Node * p15 = new Node (15 );
Node * p19 = new Node (19 );
 
Node * p18 = new Node (18 );
Node * p20 = new Node (20 );
P16-> left = p15;
P16-> right = p19;

P19-> left = p18;
P19-> right = p20;
Node * p10 = new Node (10, p6, p14 );
Root = p10;

Return root;
}
 
Void BTreeToLink (Node * & node, int curIndex)
{
Node * ptr;
If (node-> left)
{
BTreeToLink (node-> left, curIndex + 1 );
Node-> left-> right = node;
}
If (node-> right)
{
BTreeToLink (node-> right, curIndex + 1 );
 
Ptr = node-> right;
While (ptr-> left) // move to the node with the smallest value
Ptr = ptr-> left;
Ptr-> left = node; // connect the node
Node-> right = ptr;
While (node-> right) // points to the largest node
Node = node-> right;
}
}
Int main (int argc, char * argv [])
{
 
Node * root = create ();
Node * ptr = NULL;
BTreeToLink (root, 0 );
 
Ptr = root;
While (ptr-> left! = NULL)
{
Ptr = ptr-> left;
}
 
While (ptr)
{
Cout <ptr-> data <endl;
Ptr = ptr-> right;
}
Return 0;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.