int main() { struct BST*T; T=(struct BST*)malloc(sizeof(struct BST*)); T->root=NULL; struct BSTNode **nodeArray; nodeArray=(struct BSTNode**)malloc(sizeof(struct BstNode*)*10); nodeArray[0]=makeNode(500); nodeArray[1]=makeNode(200); nodeArray[2]=makeNode(700); nodeArray[3]=makeNode(100); nodeArray[4]=makeNode(300); nodeArray[5]=makeNode(400); nodeArray[6]=makeNode(600); nodeArray[7]=makeNode(0); nodeArray[8]=makeNode(900); nodeArray[9]=makeNode(800); BSTInsert(T,nodeArray[0]); BSTInsert(T,nodeArray[1]); BSTInsert(T,nodeArray[2]); BSTInsert(T,nodeArray[3]); BSTInsert(T,nodeArray[4]); BSTInsert(T,nodeArray[5]); BSTInsert(T,nodeArray[6]); BSTInsert(T,nodeArray[7]); BSTInsert(T,nodeArray[8]); BSTInsert(T,nodeArray[9]); inorderTraversal(T->root); return 0; }
void BSTInsert (tBSTNodePtr* RootPtr, char K, int Content) { /* Vlo¾í do stromu hodnotu Content s klíèem K. Pokud ji¾ uzel ** se zadaným klíèem existuje, nahradí se obsah uzlu novou hodnotou. ** Novì vytvoøený uzel nech» je v¾dy listem stromu. Øe¹te rekurzivnì. ** ** Tato rekurzivní implementace je ponìkud neefektivní, proto¾e se pøi ** ka¾dém rekurzivním zanoøení musí kopírovat celý integer "Content" (obecnì ** obsah uzlu). V praxi by se tento problém øe¹il napøíklad jedním ** z tìcho zpùsobù: ** - pøedáváním promìnné "Content" odkazem (v tom pøípadì je nutné dosazovat ** pøi volání promìnnou a není mo¾né pøímo zapsat hodnotu); ** - deklarací vnitøní procedury, které by se parametr pøedal odkazem; ** vnìj¹í procedura by slou¾ila jen jako obal (nevolala by se ** rekurzivnì); ** - pøi vyu¾ití pøedchozí varianty by se do rekurzivní procedury pøedával ** pøedem naplnìný nový uzel, který by se na závìr zru¹il v pøípadì, ** ¾e se uzel nepodaøilo zaøadit (pokud u¾ uzel s tímto klíèem existoval, ** pøepsal by se jen obsah, pøípadnì by se uzly vymìnily a ke zru¹ení ** by se pøedal starý uzel); ** ** Nerekurzivní varianta by v tomto pøípadì byla efektivnìj¹í jak z hlediska ** rychlosti, tak z hlediska pamì»ových nárokù. Zde v¹ak jde o ¹kolní ** pøíklad. Nedeklarujte ¾ádnou pomocnou proceduru nebo funkci, problém ** øe¹te rekurzivním voláním procedury samé. ** ** POZOR: Vzhledem k jisté slo¾itosti rekurzívního volání této fce zde uvádím ** pøíklad jak funkci zavolat (kdy¾ jsme pøijali RootPtr jako ukazatel na ** ukazatel). Správné zavolání napø. na levý podstrom: ** BSTInsert(&((*RootPtr)->LPtr), K, Content) */ if(*RootPtr == NULL){ if(!(*RootPtr = malloc(sizeof(struct tBSTNode)))){ printf("Není pamì»!\n"); } else { (*RootPtr)->Key = K; (*RootPtr)->BSTNodeCont = Content; (*RootPtr)->LPtr = NULL; (*RootPtr)->RPtr = NULL; } } else { if((*RootPtr)->Key < K) { BSTInsert(&((*RootPtr)->RPtr), K, Content); } else if((*RootPtr)->Key > K) { BSTInsert(&((*RootPtr)->LPtr), K, Content); } else { (*RootPtr)->BSTNodeCont = Content; } } }
// inserts an item at the wanted location TreeNode *BSTInsert(TreeNode * tree, Item * newItem) { // empty tree case, make a new tree with this item as the root if ( tree == NULL ) return( CreateBST(newItem, NULL, NULL) ); // duplicates go to the right if ( newItem->key < tree->item->key ) tree->pLeft = BSTInsert(tree->pLeft, newItem); else tree->pRight = BSTInsert(tree->pRight, newItem); return tree; }
BSTInsert(BSTree *tree, Elem elem) { if (*tree == NULL) { (*tree) = (BSTNode*)malloc(sizeof(BSTNode)); (*tree)->data = elem; (*tree)->lchild = (*tree)->rchild = NULL; return 0; } if (elem < (*tree)->data) { BSTInsert(&((*tree)->lchild), elem); } else { BSTInsert(&((*tree)->rchild), elem); } }
int main() { int C, N, number; scanf("%d", &C); for (int i = 1; i <= C; i++) { scanf("%d", &N); BSTree *tree = new BSTree(); while (N--) { scanf("%d", &number); BSTInsert(tree, number); } printf("Case %d:\n", i); printf("Pre.:"); preOrder(tree); printf("\n"); printf("In..:"); inOrder(tree); printf("\n"); printf("Post:"); postOrder(tree); printf("\n\n"); } return 0; }
int globalDecl() { //za decl nebrat token if ((error = testToken(T_ID)) != E_OK) return error; //ID if(BSTSearch(TempTree, T.s) != NULL){ return E_SEMA; } strInit(&IDstr); strCopystring(&IDstr, &T.s); gettoken(); if ((error = testToken(T_COLON)) != E_OK) return error; gettoken(); if ((error = testToken(T_DATATYPE)) != E_OK) return error; /******************************************INSERT***************************************************************/ if(!(strCmpConstStr(&(T.s), "boolean"))) TempVar->type = O_BOOL; if(!(strCmpConstStr(&(T.s), "integer"))) TempVar->type = O_INT; if(!(strCmpConstStr(&(T.s), "real"))) TempVar->type = O_REAL; if(!(strCmpConstStr(&(T.s), "string"))){ TempVar->type = O_STRING; strInit(&TempVar->value.sval); } BSTInsert (&TempTree, IDstr, TempVar); /******************************************INSERT***************************************************************/ gettoken(); if ((error = testToken(T_SEMICOLON)) != E_OK) return error; // ";" gettoken(); //strFree(&IDstr); if (testToken(T_ID) == E_OK) if ((error = globalDecl()) != E_OK) return error; //dalsia promena? return E_OK; }
bool RBTree<T>::Insert(T item){ bool flag = false; Node<T>* inserted_node = NULL; if (!Contains(item)){ inserted_node = BSTInsert(item); // normal BST insertion method inserted_node->is_black = false; while (inserted_node != root && !inserted_node->p->is_black){ // iterates until root or black parent is reached if (inserted_node->p == inserted_node->p->p->left){ Node<T>* uncle = inserted_node->p->p->right; // node's uncle if(!uncle->is_black){ inserted_node->p->is_black = true; uncle->is_black = true; inserted_node->p->p->is_black = false; inserted_node = inserted_node->p->p; } else {//uncle is black yo if (inserted_node == inserted_node->p->right){ inserted_node = inserted_node->p; RotateLeft(inserted_node); } inserted_node->p->is_black = true; inserted_node->p->p->is_black = false; RotateRight(inserted_node->p->p); } } if (inserted_node->p == inserted_node->p->p->right) { Node<T>* aunt = inserted_node->p->p->left; if(!aunt->is_black){ inserted_node->p->is_black = true; aunt->is_black = true; inserted_node->p->p->is_black = false; inserted_node = inserted_node->p->p; } else{ if(inserted_node == inserted_node->p->left){ inserted_node = inserted_node->p; RotateRight(inserted_node); } inserted_node->p->is_black = true; inserted_node->p->p->is_black = false; RotateLeft(inserted_node->p->p); } } } root->is_black = true;//FIXME flag = true; size++; } return flag; }
int tabSymInsertFunc(tTabSym* table, string* key, tFuncInfo* funcInfo) { //nejprve vytvorime strukturu pro data elementu tTabSymElemData* elemData = createElemData(TAB_SYM_FUNCTION, funcInfo); if (elemData == NULL) { //chyba return 0; } //vlozime do stromu return BSTInsert(&(table->root), key, elemData); }
int tabSymInsertConst(tTabSym* table, string* key, tConstantInfo* constInfo) { //nejprve vytvorime strukturu pro data elementu tTabSymElemData* elemData = createElemData(TAB_SYM_CONSTANT, constInfo); if (elemData == NULL) { //chyba return 0; } //vlozime do stromu return BSTInsert(&(table->root), key, elemData); }
int tabSymInsertVar(tTabSym* table, string* key, tVariableInfo* varInfo) { //nejprve vytvorime strukturu pro data elementu tTabSymElemData* elemData = createElemData(TAB_SYM_VARIABLE, varInfo); if (elemData == NULL) { //chyba return 0; } //vlozime do stromu return BSTInsert(&(table->root), key, elemData); }
int test_BSTInsert (tBSTNodePtr* TempTree, char K, int Content) { solved=TRUE; BSTInsert(TempTree, K, Content); if (!solved) { printf("Operace BSTInsert() nebyla implementovana \n"); return(FALSE); } else { Print_tree(*TempTree); return(TRUE); } }
BTreeNode* BSTInsert(BTreeNode **pRoot,BSTData data){ //BTreeNode *pNode=NULL; //BTreeNode *cNode=*pRoot; //BTreeNode *nNode=NULL; ////위치 찾기 //while(cNode!=NULL){ // if(data==GetData(cNode)) return; // pNode=cNode; // if(GetData(cNode)<data) cNode=GetRightSubTree(cNode); // else cNode=GetLeftSubTree(cNode); //} // //nNode=MakeBTreeNode(); //SetData(nNode,data); //if(pNode!=NULL){ //삽입 노드가 루트노드가 아닌 경우 // if(GetData(pNode)<data) MakeRightSubTree(pNode,nNode); // else MakeLeftSubTree(pNode,nNode); //} //else //삽입 되는 노드가 루트 노드가 되는 경우 // *pRoot=nNode; if(*pRoot==NULL){ *pRoot=MakeBTreeNode(); SetData(*pRoot,data); } else if(GetData(*pRoot)>data){ BSTInsert(&((*pRoot)->left),data); *pRoot=Rebalance(pRoot); } else if(GetData(*pRoot)<data){ BSTInsert(&((*pRoot)->right),data); *pRoot=Rebalance(pRoot); } else return NULL; //키(data) 중복 return *pRoot; }
BSTree* BSTInsert(BSTree *originalTree, int input) { BSTree *newtree = new BSTree(); newtree -> value = input; if (originalTree -> value == 0) { originalTree -> value = input; } else if (input < originalTree -> value) { if (originalTree -> leftChild == NULL) { originalTree -> leftChild = newtree; } else { BSTInsert(originalTree -> leftChild, input); } } else { if (originalTree -> rightChild == NULL) { originalTree -> rightChild = newtree; } else { BSTInsert(originalTree -> rightChild, input); } } return newtree; }
void BSTInsert (tBSTNodePtr* RootPtr, char K, int Content) { /* --------- ** Vlo¾í do stromu RootPtr hodnotu Content s klíèem K. ** ** Pokud ji¾ uzel se zadaným klíèem ve stromu existuje, bude obsah uzlu ** s klíèem K nahrazen novou hodnotou. Pokud bude do stromu vlo¾en nový ** uzel, bude vlo¾en v¾dy jako list stromu. ** ** Funkci implementujte rekurzivnì. Nedeklarujte ¾ádnou pomocnou funkci. ** ** Rekurzivní implementace je ménì efektivní, proto¾e se pøi ka¾dém ** rekurzivním zanoøení ukládá na zásobník obsah uzlu (zde integer). ** Nerekurzivní varianta by v tomto pøípadì byla efektivnìj¹í jak z hlediska ** rychlosti, tak z hlediska pamì»ových nárokù. Zde jde ale o ¹kolní ** pøíklad, na kterém si chceme ukázat eleganci rekurzivního zápisu. **/ if ( *RootPtr != NULL ){ // pokud strom neni prazdny, hledej nove misto if ( (*RootPtr)->Key < K ) BSTInsert(&((*RootPtr)->RPtr), K, Content); // hledej v levem podstromu else if ( (*RootPtr)->Key > K ) BSTInsert(&((*RootPtr)->LPtr), K, Content); // hledej v pravem podstromu else (*RootPtr)->BSTNodeCont = Content; }else{ // strom je prazdny tBSTNodePtr new_ptr; // vytvor uzel new_ptr = malloc(sizeof(struct tBSTNode)); if ( new_ptr == NULL ) return; // ukonci new_ptr->Key = K; new_ptr->BSTNodeCont = Content; new_ptr->LPtr = NULL; new_ptr->RPtr = NULL; *RootPtr = new_ptr; } }
void BSTInsert (tBSTNodePtr* RootPtr, char K, int Content) { if ( *RootPtr == NULL ) { /* Vytvori novy uzel stromu */ *RootPtr = malloc ( sizeof ( struct tBSTNode ) ) ; /* Vlozi hodnotu Content a klic K */ ( *RootPtr ) -> Key = K ; ( *RootPtr ) -> BSTNodeCont = Content ; ( *RootPtr ) -> LPtr = NULL ; ( *RootPtr ) -> RPtr = NULL ; } else { /* Pokud je klic vetsi nez K */ if ( ( *RootPtr ) -> Key > K ) { /* Pokracuje v levem podstromu */ BSTInsert ( ( &( *RootPtr ) -> LPtr ) , K , Content ) ; return ; } /* Pokud je klic mensi nez K */ else if ( ( *RootPtr ) -> Key < K ) { /* Pokracuje v pravem podstromu */ BSTInsert ( ( &( *RootPtr ) -> RPtr ) , K , Content ) ; return ; } /* Jinak nahradi obsah uzlu novou hodnotou */ else { ( *RootPtr ) -> BSTNodeCont = Content ; } } }
int main(void) { BSTree tree = NULL; int a[9]= { 16,8,4,3,6,10,9,46,97 }; for (int i = 0; i < 9; i++) { BSTInsert(&tree, a[i]); } BSTDelete(&tree, 16); BSTMidTravserse(tree); //int max = BSTDepth(tree,0); //printf("\nMaxBSTDepth = %d \n", max); //Qsort(a, 0, 5); /*for (int i = 0; i < 6; i++) { printf("%d ", a[i]); }*/ }
void BSTInsert (tBSTNodePtr* RootPtr, char K, int Content) { /* --------- ** Vlo¾í do stromu RootPtr hodnotu Content s klíèem K. ** ** Pokud ji¾ uzel se zadaným klíèem ve stromu existuje, bude obsah uzlu ** s klíèem K nahrazen novou hodnotou. Pokud bude do stromu vlo¾en nový ** uzel, bude vlo¾en v¾dy jako list stromu. ** ** Funkci implementujte rekurzivnì. Nedeklarujte ¾ádnou pomocnou funkci. ** ** Rekurzivní implementace je ménì efektivní, proto¾e se pøi ka¾dém ** rekurzivním zanoøení ukládá na zásobník obsah uzlu (zde integer). ** Nerekurzivní varianta by v tomto pøípadì byla efektivnìj¹í jak z hlediska ** rychlosti, tak z hlediska pamì»ových nárokù. Zde jde ale o ¹kolní ** pøíklad, na kterém si chceme ukázat eleganci rekurzivního zápisu. **/ if (*RootPtr == NULL) { // alokace mista pro novy prvek *RootPtr = malloc(sizeof(struct tBSTNode)); // naplneni prvniho prvku ve stromu (*RootPtr)->Key = K; (*RootPtr)->BSTNodeCont = Content; (*RootPtr)->LPtr = NULL; (*RootPtr)->RPtr = NULL; } else if (K < (*RootPtr)->Key) { // vlozeni do leve vetve BSTInsert(&(*RootPtr)->LPtr, K, Content); } else if (K > (*RootPtr)->Key) { // vlozeni do prave vetve BSTInsert(&(*RootPtr)->RPtr, K, Content); } else { // prepsani hodnoty, pokud jsou klice stejne (*RootPtr)->BSTNodeCont = Content; } }
void BSTInsert (tBSTNodePtr* RootPtr, char K, int Content) { /* --------- ** Vlo¾í do stromu RootPtr hodnotu Content s klíèem K. ** ** Pokud ji¾ uzel se zadaným klíèem ve stromu existuje, bude obsah uzlu ** s klíèem K nahrazen novou hodnotou. Pokud bude do stromu vlo¾en nový ** uzel, bude vlo¾en v¾dy jako list stromu. ** ** Funkci implementujte rekurzivnì. Nedeklarujte ¾ádnou pomocnou funkci. ** ** Rekurzivní implementace je ménì efektivní, proto¾e se pøi ka¾dém ** rekurzivním zanoøení ukládá na zásobník obsah uzlu (zde integer). ** Nerekurzivní varianta by v tomto pøípadì byla efektivnìj¹í jak z hlediska ** rychlosti, tak z hlediska pamì»ových nárokù. Zde jde ale o ¹kolní ** pøíklad, na kterém si chceme ukázat eleganci rekurzivního zápisu. **/ if(*RootPtr!=NULL){ if((*RootPtr)->Key==K) //aktualize prvku (*RootPtr)->BSTNodeCont=Content; else if((*RootPtr)->Key>K)//prvek je u leveho syna BSTInsert(&((*RootPtr)->LPtr),K,Content); else //prvek je u praveho syna BSTInsert(&((*RootPtr)->RPtr),K,Content); } //dosli jsme na konec stromu -> pridani prvku else{ *RootPtr = malloc(sizeof(struct tBSTNode)); if(*RootPtr==NULL) return;//chyba alokace else{ (*RootPtr)->LPtr = NULL; (*RootPtr)->RPtr = NULL; (*RootPtr)->Key = K; (*RootPtr)->BSTNodeCont = Content; } } }
Node<T>* RedBlackTree<T>::CopyTree(Node<T>* thisnode, Node<T>* sourcenode, Node<T>* parentnode) { Node<T>* nd = NULL; if (sourcenode != NULL) { // Do normal pre-order binary search tree insertion to make sure that I have the same // structure as the passed in tree, with a little addition of copying the passed in tree colors // to make an identical red-black tree copy. nd = BSTInsert(sourcenode->data); ++size; nd->is_black = sourcenode->is_black; CopyTree(NULL, sourcenode->left, parentnode); // I did not use thisnode argument for this function, CopyTree(NULL, sourcenode->right, parentnode); // so I call the next recursive function with NULL } // for thisnode argument. // I used parentnode as an indicator of the root for of rbtree so to make sure I set // the right root for this tree. if (sourcenode == parentnode) { root = nd; } return NULL; }
void main(){ BiTree T=NULL,p; DataType table[]={37,32,35,62,82,95,73,12,5}; int n=sizeof(table)/sizeof(table[0]); DataType x={73},s={32}; int i; for(i=0;i<n;i++) BSTInsert(&T,table[i]); printf("中序遍历二叉排序树得到的序列为:\n"); InOrderTraverse(T); p=BSTSearch(T,x); if(p!=NULL) printf("\n二叉排序树查找,关键字%d存在\n",x.key); else printf("查找失败!\n"); BSTDelete(&T,s); printf("删除元素%d后,中序遍历二叉排序树得到的序列为:\n",s.key); InOrderTraverse(T); printf("\n"); system("pause"); }
int main(void) { BTreeNode * bstRoot; BTreeNode * sNode; BSTMakeAndInit(&bstRoot); BSTInsert(&bstRoot, 9); BSTInsert(&bstRoot, 1); BSTInsert(&bstRoot, 6); BSTInsert(&bstRoot, 2); BSTInsert(&bstRoot, 8); BSTInsert(&bstRoot, 3); BSTInsert(&bstRoot, 5); sNode = BSTSearch(bstRoot, 1); if(sNode == NULL) printf("탐색 실패 \n"); else printf("탐색에 성공한 키의 값: %d \n", BSTGetNodeData(sNode)); sNode = BSTSearch(bstRoot, 4); if(sNode == NULL) printf("탐색 실패 \n"); else printf("탐색에 성공한 키의 값: %d \n", BSTGetNodeData(sNode)); sNode = BSTSearch(bstRoot, 6); if(sNode == NULL) printf("탐색 실패 \n"); else printf("탐색에 성공한 키의 값: %d \n", BSTGetNodeData(sNode)); sNode = BSTSearch(bstRoot, 7); if(sNode == NULL) printf("탐색 실패 \n"); else printf("탐색에 성공한 키의 값: %d \n", BSTGetNodeData(sNode)); return 0; }
int localDecl() { //za decl nebrat token if ((error = testToken(T_ID)) != E_OK) return error; //ID if (searchParam(paramlist, &(T.s)) != NULL){ //zde budu muset nejspis dat jen jmenu aktualni fkce return E_SEMA; } if(strCmpstring(&(T.s), &ActFun) == 0){ //ADDED return E_SEMA; } if(BSTSearch (TempTreeL, T.s) != NULL){ return E_SEMA; } strInit(&IDstr); strCopystring(&IDstr, &T.s); gettoken(); if ((error = testToken(T_COLON)) != E_OK) return error; gettoken(); if ((error = testToken(T_DATATYPE)) != E_OK) return error; // typ /******************************************INSERT***************************************************************/ if(!(strCmpConstStr(&(T.s), "boolean"))) TempVar->type = O_BOOL; if(!(strCmpConstStr(&(T.s), "integer"))) TempVar->type = O_INT; if(!(strCmpConstStr(&(T.s), "real"))) TempVar->type = O_REAL; if(!(strCmpConstStr(&(T.s), "string"))){ TempVar->type = O_STRING; strInit(&TempVar->value.sval); } BSTInsert (&TempTreeL, IDstr, TempVar); /******************************************INSERT***************************************************************/ gettoken(); if ((error = testToken(T_SEMICOLON)) != E_OK) return error; // ";" gettoken(); //strFree(&IDstr); if (testToken(T_ID) == E_OK) if ((error = localDecl()) != E_OK) return error; //dalsia promena? return E_OK; }
int main(void) { BTreeNode* bstRoot; BTreeNode* sNode; BSTMakeAndInit(&bstRoot); BSTInsert(&bstRoot, 5); BSTInsert(&bstRoot, 8); BSTInsert(&bstRoot, 1); BSTInsert(&bstRoot, 6); BSTInsert(&bstRoot, 4); BSTInsert(&bstRoot, 9); BSTInsert(&bstRoot, 3); BSTInsert(&bstRoot, 2); BSTInsert(&bstRoot, 7); BSTShowAll(bstRoot); printf("\n"); sNode = BSTSearch(bstRoot, 1); if(sNode == NULL) printf("search fail!\n"); else printf("key : %d\n", BSTGetNodeData(sNode)); printf("-------------------------------------------\n"); sNode = BSTSearch(bstRoot, 4); if(sNode == NULL) printf("search fail!\n"); else printf("key : %d\n", BSTGetNodeData(sNode)); printf("-------------------------------------------\n"); sNode = BSTSearch(bstRoot, 6); if(sNode == NULL) printf("search fail!\n"); else printf("key : %d\n", BSTGetNodeData(sNode)); printf("-------------------------------------------\n"); sNode = BSTSearch(bstRoot, 7); if(sNode == NULL) printf("search fail!\n"); else printf("key : %d\n", BSTGetNodeData(sNode)); printf("-------------------------------------------\n"); BSTShowAll(bstRoot); printf("\n"); sNode = BSTRemove(&bstRoot, 3); free(sNode); printf("Remove 3-------------------------------------------\n"); BSTShowAll(bstRoot); printf("\n"); sNode = BSTRemove(&bstRoot, 8); free(sNode); printf("Remove 8-------------------------------------------\n"); BSTShowAll(bstRoot); printf("\n"); sNode = BSTRemove(&bstRoot, 1); free(sNode); printf("Remove 1-------------------------------------------\n"); BSTShowAll(bstRoot); printf("\n"); sNode = BSTRemove(&bstRoot, 6); free(sNode); printf("Remove 6-------------------------------------------\n"); BSTShowAll(bstRoot); printf("\n"); return 0; }
int main(int argc, char *argv[]) { printf("Binarni vyhledavaci strom\n"); printf("=========================\n"); printf("[TEST01]\n"); printf("Test inicializace....\n"); test_BSTInit(&TempTree); printf("[TEST02]\n"); printf("Vypocitame vysku stromu\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); test_BSTHeight(TempTree); printf("[TEST03]\n"); printf("Zkusime zrusit strom\n"); printf("~~~~~~~~~~~~~~~~~~~~\n"); test_BSTDispose(&TempTree); printf("[TEST04]\n"); printf("Pokusime se vyhledat polozku s klicem 'A' -- nenalezne se\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'A'; test_BSTSearch(TempTree,K,&Content_of_Search); printf("[TEST05]\n"); printf("Vlozime prvni prvek (H,1)\n"); K = 'H'; Content_of_Insert=1; test_BSTInsert(&TempTree,K,Content_of_Insert); printf("[TEST06]\n"); printf("Vypocitame vysku stromu\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); test_BSTHeight(TempTree); printf("[TEST07]\n"); printf("Pokusime se vyhledat polozku s klicem H\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); test_BSTSearch(TempTree,K,&Content_of_Search); printf("[TEST08]\n"); printf("Vlozime prvek (H,8) - pouze zmena hodnoty\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); Content_of_Insert=8; test_BSTInsert(&TempTree,K,Content_of_Insert); printf("[TEST09]\n"); printf("Vlozime dalsi prvky a vytvorime tak symetricky binarni strom \n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n"); BSTInsert(&TempTree,'D',4); BSTInsert(&TempTree,'L',12); BSTInsert(&TempTree,'B',2); BSTInsert(&TempTree,'F',6); BSTInsert(&TempTree,'J',10); BSTInsert(&TempTree,'N',14); BSTInsert(&TempTree,'A',1); BSTInsert(&TempTree,'C',3); BSTInsert(&TempTree,'E',5); BSTInsert(&TempTree,'G',7); BSTInsert(&TempTree,'I',9); BSTInsert(&TempTree,'K',11); BSTInsert(&TempTree,'M',13); BSTInsert(&TempTree,'O',16); Print_tree(TempTree); printf("[TEST10]\n"); printf("Vypocitame vysku stromu\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); test_BSTHeight(TempTree); printf("[TEST11]\n"); printf("Pokusime se vyhledat polozky s klici 'A', 'B'\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K='A'; test_BSTSearch(TempTree,K,&Content_of_Search); K='B'; test_BSTSearch(TempTree,K,&Content_of_Search); printf("[TEST12]\n"); printf("Pokusime se vyhledat polozky s klici 'X', 'Y'\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K='X'; test_BSTSearch(TempTree,K,&Content_of_Search); K='Y'; test_BSTSearch(TempTree,K,&Content_of_Search); printf("[TEST13]\n"); printf("Pridame vhodne jeste dalsi prvky \n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n"); BSTInsert(&TempTree,'S',10); BSTInsert(&TempTree,'R',10); BSTInsert(&TempTree,'Q',10); BSTInsert(&TempTree,'P',10); BSTInsert(&TempTree,'X',10); BSTInsert(&TempTree,'Y',10); BSTInsert(&TempTree,'Z',10); Print_tree(TempTree); printf("[TEST14]\n"); printf("Vypocitame vysku stromu\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); test_BSTHeight(TempTree); printf("[TEST15]\n"); printf("Zrusime listovy uzel (A,1)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'A'; test_BSTDelete(&TempTree,K); printf("[TEST16]\n"); printf("Zrusime uzel, ktery ma jen levy podstrom (R,10)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'R'; test_BSTDelete(&TempTree, K); printf("[TEST17]\n"); printf("Vypocitame vysku stromu\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); test_BSTHeight(TempTree); printf("[TEST18]\n"); printf("Zrusime uzel, ktery ma jen pravy podstrom (X,10)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n"); K = 'X'; test_BSTDelete(&TempTree, K); printf("[TEST19]\n"); printf("Zrusime uzel, ktery ma oba podstromy (L,12)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'L'; test_BSTDelete(&TempTree, K); printf("[TEST20]\n"); printf("Pokusime se zrusit uzel, ktery neexistuje (U,?)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'U'; test_BSTDelete(&TempTree, K); printf("[TEST21]\n"); printf("Zrusime korenovy uzel (H,8)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'H'; test_BSTDelete(&TempTree, K); printf("[TEST22]\n"); printf("Zrusime dalsi uzel (K,11)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'K'; test_BSTDelete(&TempTree, K); printf("[TEST23]\n"); printf("Zrusime dalsi uzel (D,4)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'D'; test_BSTDelete(&TempTree, K); printf("[TEST24]\n"); printf("Zrusime dalsi uzel (S,10)\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~\n"); K = 'S'; test_BSTDelete(&TempTree, K); printf("[TEST25]\n"); printf("Nakonec zrusime cely strom\n"); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); test_BSTDispose(&TempTree); printf("------------------------------ konec -------------------------------------\n"); return(0); }
bool RedBlackTree<T>::Insert(T item) { if (Search(item) == true) { // Make sure no similar item to the passed in one exists in the tree. return false; } Node<T>* x = BSTInsert(item); // Normal binary tree insertion. ++size; // Mainly used to make sure that root assignment in the BSTInsert only done once if there are more than // one item in the tree. // Everything below is just to fix the tree after binary insertion. if (x != NULL) { // This condition might not be necessary but just to make // sure that there is an item that was inserted (i.e. BSTInsert did not return NULL). x->is_black = false; Node<T>* y = NULL; while (x != root && x->p != NULL && x->p->is_black == false) { // Iterate until root or parent is reached. if (x->p->p != NULL && x->p == x->p->p->left) { if (x->p != NULL && x->p->p != NULL) { y = x->p->p->right; // "Uncle" of x. } if (y != NULL && y->is_black == false) { // Same as x->p. x->p->is_black = true; y->is_black = true; x->p->p->is_black = false; x = x->p->p; } else { // y->is_black = true. if (x->p != NULL && x == x->p->right) { x = x->p; LeftRotate(x); } if (x->p != NULL && x->p->p != NULL) { x->p->is_black = true; x->p->p->is_black = false; RightRotate(x->p->p); } } } else { // Symmetric to the case above, by changing every left word with right, // and every left rotation with right rotation. if (x->p != NULL && x->p->p != NULL) { y = x->p->p->left; } if (y != NULL && y->is_black == false) { x->p->is_black = true; y->is_black = true; x->p->p->is_black = false; x = x->p->p; } else { if (x->p != NULL && x == x->p->left) { x = x->p; RightRotate(x); } if (x->p != NULL && x->p->p != NULL) { x->p->is_black = true; x->p->p->is_black = false; LeftRotate(x->p->p); } } } } } root->is_black = true; return true; }
void PollingWorker::PollRS232() { char * readBuf; char * rawByte; char * unCompressed; Header * headerBuffer; Item * sender; long numBytesToGet; char receiveID; DWORD dwCommEvent, dwBytesTransferred; Msg * newMsg; isFinish = 0; while(!isFinish) { SetUpDCB(baudRate); // set up the mask, EV_RXCHAR is the event when we receive a character if (!SetCommMask(hComm, EV_RXCHAR)) emit error(QString("Error setting communications mask."), (int)GetLastError()); // wait for a character to come in if (!WaitCommEvent(hComm, &dwCommEvent, NULL)) emit error(QString("Error waiting for a character."), (int)GetLastError()); // we have a character, read the header to see if its good else { if(!isRaw->isChecked()) { // set up the header buffer if(!(headerBuffer = (Header *)malloc(sizeof(struct Header)))) emit error(QString("Error malloccing headerBuffer."), (int)GetLastError()); // get the header if(!ReadFile(hComm, (BYTE *)headerBuffer, HEADERSIZE, &dwBytesTransferred, 0)) emit error(QString("Error getting the header buffer."), (int)GetLastError()); if(headerBuffer->lSignature == 0xDEADBEEF) { // get the data length from the header numBytesToGet = headerBuffer->lDataLength; readBuf = (char*)calloc(numBytesToGet,sizeof(char)); if (readBuf == NULL) emit error(QString("Error mallocing readBuf."), (int)GetLastError()); // get the message if(!ReadFile(hComm, readBuf, numBytesToGet, &dwBytesTransferred, 0)) emit error(QString("Error getting the message."), (int)GetLastError()); emit error(QString("Bytes gotten"), (int)(dwBytesTransferred)); unCompressed = readBuf; // calculate the checksum and compare if(headerBuffer->sChecksum != CalculateChecksum(readBuf, headerBuffer->lDataLength)) { emit transmitError(); //emit error (QString ("Checksum reports errors"),0); } if (headerBuffer->bVersion == 0xFF) { if(!(unCompressed = (char *)calloc(headerBuffer->lDataUncompressed,sizeof(char)))) emit error(QString("Error malloccing unCompressed."), (int)GetLastError()); Huffman_Uncompress((unsigned char*)readBuf, (unsigned char*)unCompressed, headerBuffer->lDataLength, headerBuffer->lDataUncompressed); // For testing purposes. emit error (QString("We have a Huffman buffer."),0); }else if (headerBuffer->bVersion == 0xF0) { if(!(unCompressed = (char *)calloc(headerBuffer->lDataUncompressed,sizeof(char)))) emit error(QString("Error malloccing unCompressed."), (int)GetLastError()); unCompressed = RunLengthDecode(readBuf, headerBuffer->lDataLength); // For testing purposes. emit error (QString("We have an RLE buffer."),0); }else if (headerBuffer->bVersion == 0x0F) { if(!(unCompressed = (char *)calloc(headerBuffer->lDataUncompressed,sizeof(char)))) emit error(QString("Error malloccing unCompressed."), (int)GetLastError()); unCompressed = (char*)DifferentialExpand(readBuf, headerBuffer->lDataLength); // For testing purposes. emit error (QString("We have a Differential buffer."),0); } else emit error (QString("We have an uncompressed buffer."),0); receiveID = GetReceiverId(headerBuffer->lReceiverAddr); if (headerBuffer->bDataType == 0) { // If the data is text. // create a new message structure and put it on the queue // not all the header options we need are available - ask Jack! if(!(newMsg = (Msg *)malloc(sizeof(struct message)))) emit error(QString("Error malloccing newMsg."), (int)GetLastError()); strcpy(newMsg->txt, unCompressed); newMsg->senderID = headerBuffer->bSenderAddr; newMsg->receiverID = (short)receiveID; newMsg->msgNum = rand() % 100; newMsg->priority = headerBuffer->bPriority; AddToQueue(newMsg); // Check if the senderID has already been created. If not, create one. if ((sender = BSTSearch(root, headerBuffer->bSenderAddr))== NULL) { Item * newItem = (Item*)(malloc (sizeof(Item))); int * count = (int*)(malloc (sizeof(int))); *count = 1; newItem->key = headerBuffer->bSenderAddr; newItem->data = count; root = BSTInsert(root,newItem); } else // If it has been created, increment *((int*)sender->data) = *((int*)sender->data) + 1; emit labelEdit(QString("Number of Messages: %1").arg(numberOfMessages)); } else { // we have audio, emit the data, the length of the data, and the sample rate emit audioReceived(headerBuffer->lDataUncompressed, unCompressed, headerBuffer->sSamplesPerSec); } } } else { // in raw mode, just grab chunks of bytes as they come do { if(!(rawByte = (char *)calloc(1, sizeof(char)))) emit error(QString("Error malloccing rawByte."), (int)GetLastError()); if(!ReadFile(hComm, rawByte, 1, &dwBytesTransferred, 0)) emit error(QString("Error getting the raw data."), (int)GetLastError()); if(dwBytesTransferred != 0) emit messageEdit(*rawByte); }while(dwBytesTransferred != 0); } } } emit finished(); }
bool RedBlackTree<T>::Insert(T item) { //item already exist if (Search(item) == true) { return false; } Node<T>* x = BSTInsert(item); if (x == NULL) { return false; } size++; x->is_black = false; while (x != root && !x->p->is_black) { //y is uncle x is left child if (x->p == x->p->p->left) { Node<T>* y = x->p->p->right; //uncle and parent both red y could be null? if (y != NULL && !y->is_black) { //grand[arent turn to red;uncle and parent turn to black x->p->is_black = true; y->is_black = true; x->p->p->is_black = false; x = x->p->p; } else { if (x == x->p->right) { x = x->p; LeftRotate(x); } x->p->is_black = true; x->p->p->is_black = false; RightRotate(x->p->p); } } else { //x.p ==x.p.p.right Node<T>* y = x->p->p->left; if (y != NULL && !y->is_black) { x->p->is_black = true; y->is_black = true; x->p->p->is_black = false; x = x->p->p; } else { if (x == x->p->left) { x = x->p; RightRotate(x); } x->p->is_black = true; x->p->p->is_black = false; LeftRotate(x->p->p); } } } root->is_black = true; return true; }