Advertisement
Guest User

sum_greater full example code

a guest
Aug 2nd, 2017
494
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.40 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. struct bstnode {
  5.   int item;
  6.   struct bstnode* left;
  7.   struct bstnode* right;
  8. };
  9.  
  10. struct bst {
  11.   struct bstnode* root;
  12. };
  13.  
  14. int binsert(struct bstnode **root, int info){
  15.     if(!*root){
  16.         *root = malloc(sizeof(struct bstnode));
  17.         (*root)->item = info;
  18.         (*root)->left = NULL;
  19.         (*root)->right = NULL;
  20.     } else
  21.         return (info > (*root)->item) ? \
  22.             binsert(&((*root)->right), info) : \
  23.             binsert(&(*root)->left, info);
  24.  
  25.     return 0;
  26. }
  27.  
  28. int sum_greater(struct bst * t, int num){
  29.  
  30.     struct bstnode *ptr = t->root;
  31.     if(!ptr)
  32.         return 0;
  33.  
  34.     struct bst right_tree = { t->root->right };
  35.     struct bst left_tree = { t->root->left };
  36.        
  37.     if(ptr->item > num)
  38.         return ptr->item + \
  39.             sum_greater(&left_tree, num) + \
  40.                 sum_greater(&right_tree, num);
  41.     else // ptr->item =< num
  42.         return sum_greater(&right_tree, num);
  43. }
  44.  
  45. void inordre(struct bstnode *root){
  46.     if(root){
  47.         inordre(root->left);
  48.         printf("%d\n", root->item);
  49.         inordre(root->right);
  50.     }
  51. }
  52.  
  53. int main(){
  54.  
  55.     struct bstnode *root = NULL;
  56.     int val[] = {100, 50, 200, 25, 75, 150, 250, 15, 35, 65, 85, 120, 170, 230, 300};
  57.         int i;
  58.    
  59.         for(i = 0; i < sizeof(val)/sizeof(int); i++)
  60.             binsert(&root, val[i]);
  61.  
  62.     inordre(root);
  63.  
  64.     struct bst t = {root};
  65.     printf("sum:%d\n", sum_greater(&t, 26));
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement