[C]-binary sorting tree

Source: Internet
Author: User

Source: Network

  # Include  <  Stdio. h  >  
# Include < Stdlib. h >

Struct Nodb
{
Int Data;
Struct Nodb * LCH, * RCH;
};
Struct Nodb * Root, * Q, * P;

Void Insert1 ( Struct Nodb * S );

Void Creat ()
{
Struct Nodb * S;
Int I, N, K;
Printf ( " N =? " );
Scanf ( " % D " , & N );

For (I = 1 ; I < N; I ++ )
{
Printf ( " K % d =? " , I );
Scanf ( " % D " , & K );
S = ( Struct Nodb * ) Malloc ( Sizeof ( Struct Nodb ));
S -> Data = K; s -> Lch = NULL; s -> RCH = NULL;
Insert1 (s );
}
}


Void Insert1 ( Struct Nodb * S)
{ // Non-recursive insert
Struct Nodb * P, * Q;
If (Root = Null)
Root = S;
Else
{
P = Root;
While (P ! = Null)
{
Q = P; // When P moves to the child node, Q records the location of the parent node of P.
If (S -> Data < P -> Data)
P = P -> Lch;
Else
P = P -> RCH;
}
If (S -> Data < Q -> Data)
Q -> Lch = S;
Else
Q -> RCH = S; // When P is null, Q is the place to insert.
}
}

Void Print ( Struct Nodb * T)
{
If (T ! = Null)
{
Print (T -> LCH );
Printf ( " % 6d " , T -> Data );
Print (T -> RCH );
}
}

Void Bstsrch ( Struct Nodb * T, Int K)
{
Int Flag;
P = NULL;
Q = T;
Flag = 0 ;
While (Q ! = Null) && (Flag = 0 ))
{
If (Q -> Data = K)
{
Printf ( " % 5d found " , Q -> Data );
Flag = 1 ;
}
Else If (K < Q -> Data)
{
P = Q;
Q = Q -> Lch;
}
Else
{
P = Q;
Q = Q -> RCH;
}
}
If (Flag = 0 ) Printf ( " No node found " );
}

Void Bstins ( Struct Nodb * T, Int K)
{
Struct Nodb * R;
Bstsrch (root, k );
If (Q = Null)
{
R = ( Struct Nodb * ) Malloc ( Sizeof ( Struct Nodb ));
R -> Data = K;
R -> Lch = NULL;
R -> RCH = NULL;
If (Root = Null)
Root = R;
Else If (K < P -> Data)
P -> Lch = R;
Else
P -> RCH = R;
}
}

Main ()
{
Int N;
Root = 0 ;
Creat ();
Print (Root );
Printf ( " Enter key value n =? " );
Scanf ( " % D " , & N );
Bstsrch (root, N );
Printf ( " \ N " );
Bstins (root, N );
Print (Root );
}

 

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.