Expand|Select|Wrap|Line Numbers
- struct AvlNode* Insert( gint X, struct AvlNode* T )
- {
- static struct AvlNode *Parent;
- static struct AvlNode *Root;
- static int level = 0;
- if(Parent && T != NULL)
- printf("\n\nThe Root is %d and the Parent is %d", T->Element, Parent->Element);
- if(T!= NULL)
- printf(" But T is %d \n", T->Element);
- if( T == NULL )
- {
- /* Create and return a one-node tree */
- T = g_malloc( sizeof( struct AvlNode ) );
- if( T == NULL )
- printf( "Error: Out of space!" );
- else
- {
- T->Element = X; T->Height = 0;
- T->Left = T->Right = NULL;
- //Special Case for Root Node
- if(FIRST_TIME)
- {
- T->rect_x = app.drawing_area->allocation.width/2 - 25;
- T->rect_y = 0;
- draw_node(T, app);
- Root = T;
- FIRST_TIME = 0;
- }
- }
- }
- else
- if( X < T->Element )
- {
- printf("\n%d is less than %d\n", X, T->Element);
- Parent = T;
- ++level;
- T = Insert( X, T->Left );
- --level; //Finished Insert Call, decrement recursive level
- if(level == 0)
- T->Parent = Parent;
- //Draw T's Left Node to Screen
- LEFT_NODE = 1;
- T->rect_x = T->Parent->rect_x;
- T->rect_y = T->Parent->rect_y;
- draw_node(T, app);
- LEFT_NODE = 0;
- if( Height( T->Left ) - Height( T->Right ) == 2 )
- {
- printf("Performing Left Rebalancing\n");
- if( X < ( (T->Left)->Element ) )
- T = SingleRotateWithLeft( T );
- else
- T = DoubleRotateWithLeft( T );
- }
- }
- else
- if( X > T->Element )
- {
- printf("\n%d is greater than %d\n", X, T->Element);
- Parent = T;
- ++level;
- T = Insert( X, T->Right );
- --level;
- if(level == 0)
- T->Parent = Parent;
- //Draw Right Node
- RIGHT_NODE = 1;
- T->rect_x = T->Parent->rect_x;
- T->rect_y = T->Parent->rect_y;
- //Draw T's Right Node to Screen
- draw_node(T, app);
- RIGHT_NODE = 0;
- if( Height( T->Right ) - Height( T->Left ) == 2 )
- {
- printf("Performing Right Rebalancing\n");
- if( X > ( (T->Right)->Element) )
- T = SingleRotateWithRight( T );
- else
- T = DoubleRotateWithRight( T );
- }
- }
- /* Else X is in the tree already; we'll do nothing */
- T->Height = Max( Height( T->Left ), Height( T->Right ) ) + 1;
- return T;
- }