Ievietošana
Ievietošanas funkcija tiek izmantota, lai binārajā meklēšanas kokā pievienotu jaunu elementu atbilstošā vietā. Ievietošanas funkcija ir jāveido tā, lai tai pie katras vērtības mezglam ir jāpārkāpj binārā meklēšanas koka īpašība.
- Piešķiriet koka atmiņu.
- Iestatiet datu daļu uz vērtību un iestatiet koka kreiso un labo rādītāju, norādiet uz NULL.
- Ja ievietojamais vienums būs pirmais koka elements, tad šī mezgla kreisā un labā puse norādīs uz NULL.
- Pretējā gadījumā pārbaudiet, vai vienums ir mazāks par koka saknes elementu, ja tā ir patiesība, tad rekursīvi veiciet šo darbību ar saknes kreiso pusi.
- Ja tas ir nepatiess, veiciet šo darbību rekursīvi ar saknes labo apakškoku.
Ievietot (TREE, ITEM)
Piešķirt atmiņu TREE
IESTATĪT KOKU -> DATI = ITEM
SET TREE -> LEFT = TREE -> RIGHT = NULL
CITS
JA PRECE DATI
Ievietot (KOKS —> PA kreisi, VIETU)
CITS
Ievietot (KOKS —> PA labi, VIETU)
[JA BEIGAS]
[JA BEIGAS]
C Funkcija
#include #include void insert(int); struct node { int data; struct node *left; struct node *right; }; struct node *root; void main () { int choice,item; do { printf('
Enter the item which you want to insert?
'); scanf('%d',&item); insert(item); printf('
Press 0 to insert more ?
'); scanf('%d',&choice); }while(choice == 0); } void insert(int item) { struct node *ptr, *parentptr , *nodeptr; ptr = (struct node *) malloc(sizeof (struct node)); if(ptr == NULL) { printf('can't insert'); } else { ptr -> data = item; ptr -> left = NULL; ptr -> right = NULL; if(root == NULL) { root = ptr; root -> left = NULL; root -> right = NULL; } else { parentptr = NULL; nodeptr = root; while(nodeptr != NULL) { parentptr = nodeptr; if(item data) { nodeptr = nodeptr -> left; } else { nodeptr = nodeptr -> right; } } if(item data) { parentptr -> left = ptr; } else { parentptr -> right = ptr; } } printf('Node Inserted'); } } Izvade
Enter the item which you want to insert? 12 Node Inserted Press 0 to insert more ? 0 Enter the item which you want to insert? 23 Node Inserted Press 0 to insert more ? 1