Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdbool.h>
- #include <stdio.h>
- typedef struct bstnode_t {
- long long key,pos;
- struct bstnode_t \
- *left, *right;
- } BSTNode;
- typedef struct bst_t {
- BSTNode *_root;
- unsigned int _size;
- } BST;
- BSTNode* __bst__createNode(long long value) {
- BSTNode *newNode = (BSTNode*) malloc(sizeof(BSTNode));
- newNode->key = value;
- newNode->pos= 0;
- newNode->left = newNode->right = NULL;
- return newNode;
- }
- //long long __bst__position(BSTNode *root)
- //
- //{
- // if(root == NULL) return 0;
- // else
- // return (__bst__position(root->left) + 1 + __bst__position(root->right));
- //}
- BSTNode* __bst__insert(BSTNode *root, long long value) {
- BSTNode *temp = NULL;
- if (root == NULL)
- {
- temp = __bst__createNode(value);
- // temp->pos = __bst__position(temp);
- return temp;
- }
- if (value < root->key)
- {
- root->left = __bst__insert(root->left, value);
- }
- else if (value > root->key)
- {
- root->pos++;
- root->right = __bst__insert(root->right, value);
- }
- return root;
- }
- BSTNode* __bst__search(BSTNode *root, int value) {
- while (root != NULL) {
- if (value < root->key)
- root = root->left;
- else if (value > root->key)
- root = root->right;
- else
- return root;
- }
- return root;
- }
- /**
- * PRIMARY FUNCTION
- * ---------------------------
- * Accessible and safe to use.
- */
- void bst_init(BST *bst) {
- bst->_root = NULL;
- bst->_size = 0u;
- }
- bool bst_isEmpty(BST *bst) {
- return bst->_root == NULL;
- }
- long long bst_post(BSTNode *bst, long long value) {
- BSTNode *temp = bst;
- if (temp == NULL)
- return -1;
- if( temp->key > value)
- {
- long long index = bst_post(temp->left, value);
- if(index == -1) return -1;
- else return index + temp->pos +1;
- } else if (temp->key<value)
- {
- return bst_post(temp->right, value);
- }
- else
- return temp->pos;
- }
- bool bst_find(BST *bst, int value) {
- BSTNode *temp = __bst__search(bst->_root, value);
- if (temp == NULL)
- return false;
- if (temp->key == value)
- return true;
- else
- return false;
- }
- void bst_insert(BST *bst, long long value) {
- if (!bst_find(bst, value)) {
- bst->_root = __bst__insert(bst->_root, value);
- bst->_size++;
- }
- }
- int main()
- {
- BST set;
- bst_init(&set);
- int i,j;
- long long com, num, tanda=0;
- scanf("%d",&i);
- for(j=0;j<i;j++)
- {
- scanf("%lld",&com);
- if(com==1)
- {
- scanf("%lld",&num);
- bst_insert(&set,num);
- //printf("masuk %lld\n", set._root->pos);
- } else
- {
- scanf("%lld",&num);
- tanda = bst_post(set._root,num) ;
- if(tanda == -1) printf("Data tidak ada\n");
- else printf("%lld\n", tanda+1);
- }
- } return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement