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 );
}