WolfGrayy

Insert function for BST

Mar 16th, 2021
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1.  
  2.  
  3. //Inserts the item at the appropriate place in the tree. Returns `0` on success and `1` on failure. Updates the depth on the tree after each insert.
  4. int insertItem(BST* tree, void* item){
  5.      
  6. //if root isn't made, make root with passed item
  7.     if (tree->tree_root == NULL){
  8.         Node* root = createNode(item);
  9.         tree->tree_root = root;
  10.         tree->depth++;
  11.         return 0;
  12.     }
  13.  
  14.     //if not, pass recursively into the insert function, make my job easier
  15.     else{
  16.        
  17.         tree->depth++;
  18.         return insert(tree->tree_root, item);
  19.  
  20.     }
  21.  
  22. }
  23.  
  24. int insert(Node* thru, void* item){
  25.    
  26.     if(item > thru->item) // if item is greater. Should be inserted to right
  27.         thru->nodes[1] = insert(thru->nodes[1], item);
  28.     else if (item < thru->item)// item is smaller, should be inserted to left
  29.         thru->nodes[0] = insert(thru->nodes[0],item);
  30.     else
  31.         return 1;
  32.    
  33.     return 0;
  34.  
  35. }
Advertisement
Add Comment
Please, Sign In to add comment