Insert the root node of the Binary Search Tree

Source: Internet
Author: User

In the standard binary search tree, each new node is inserted somewhere at the bottom of the tree to replace an external node. This status is not an absolute requirement. You can also insert it from the root node by inserting it to the corresponding external node and then rotating it to the root node. The following shows the implementation:

# Include <stdio. h>
# Include <stdlib. h>

Struct tree
{
Int item;
Struct tree * l;
Struct tree * R;
};

Struct tree * rotr (struct tree * H)
{
If (H = NULL)
Return NULL;
Struct tree * x = NULL;
X = H-> L;
H-> L = x-> r;
X-> r = h;
Return X;
}

Struct tree * rotl (struct tree * H)
{
If (H = NULL)
Return NULL;
Struct tree * x = NULL;
X = H-> r;
H-> r = x-> L;
X-> L = h;
Return X;
}

Struct tree * insertt (struct tree * H, int item)
{
If (H = NULL)
{
H = malloc (sizeof (struct tree ));
If (H = NULL)
{
Printf ("malloc error \ n ");
Return NULL;
}
Else
{
H-> item = item;
H-> L = NULL;
H-> r = NULL;
Return h;
}
}
If (H-> item)
{
H-> L = insertt (H-> L, item );
H = rotr (h );
}
Else
{
H-> r = insertt (H-> r, item );
H = rotl (h );
}
Return h;
}

Void travel (struct tree * t)
{
If (t-> L! = NULL)
Travel (t-> L );
Printf ("% d \ n", T-> item );
If (t-> r! = NULL)
Travel (t-> r );
}

Int main (INT argc, char * argv [])
{
Struct tree * t = NULL;
T = insertt (T, 8 );
T = insertt (T, 7 );
T = insertt (T, 9 );
T = insertt (T, 6 );
T = insertt (T, 10 );
T = insertt (T, 5 );
T = insertt (T, 11 );
T = insertt (T, 4 );
T = insertt (T, 12 );
T = insertt (T, 3 );
T = insertt (T, 13 );
Travel (t );
Return 0;
}

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.