void displayTree(Node *root){ if(root == NULL ){ printf("-"); return; } if (root->letter == 'A') { if(root->left!=NULL){ printf("{"); displayTree(root->left); printf(","); printf("A,"); printf("-"); printf("}"); } else{ printf("A,"); } } if (root->letter=='B'){ if(root->left!=NULL && root->right !=NULL){ printf("{"); displayTree(root->left); printf("B,"); displayTree(root->right); printf("}"); } else{ printf("B"); } } }
int main(int argc, char* argv[]){ int array[SIZE] = {4,1,45,78,345,23,12,3,6,21}; displayArray(array,SIZE); treeNode *root = NULL; createTree(&root, array, SIZE); printf("the tree is(left->middle->right):"); displayTree(root); printf("\n"); int value = 12; treeNode* parent = NULL; int dir = -1; printf("search value %d:",value); if(searchTree(root,value) != NULL){ printf("%s\n","exist"); }else{ printf("%s\n","not exist"); } printf("delete value:%d ",value); deleteNode(&root,value); printf("\n"); printf("the tree is(left->middle->right):"); displayTree(root); printf("\n"); deleteTree(root); return 0; }
//Tree Traversal in order void displayTree(node *t) { if (t != NULL){ displayTree(t->left); printf("%d ",t->key); displayTree(t->right); } }
void displayTree(Lexeme *tree, char *head) { if(tree != NULL) { char *newHead = malloc(sizeof(char) * 1024); strcat(newHead,head); strcat(newHead,"\t"); displayTree(tree->left,newHead); printf("%s%s\n",head,displayLexeme(*tree)); displayTree(tree->right,newHead); } }
void displayTree(Node* root, int depth){ if (root == NULL) { padding (' ', depth); printf("-\n"); } else { displayTree(root->right, depth+1); padding(' ', depth); printf ( "%d\n", root->data); displayTree(root->left, depth+1); } }
//按左中右顺序遍历树 void displayTree(treeNode* node){ if(node == NULL) return; if(node->left != NULL){ displayTree(node->left); } printf("%d ",node->value); if(node->right != NULL){ displayTree(node->right); } }
// Recursive function used with printTree. Provided for you; do not modify. You should // not call this function directly. Instead, call printTree. void displayTree(Tree* root, int depth) { if (root == NULL) { padding(' ', depth); printf("-\n"); return; } displayTree(root->left, depth+4); padding(' ', depth); printf("%d\n", root->data); displayTree(root->right, depth+4); }
//Display tree void displayTree(node *pnode)// pnode is a pointeur node { // if pnode null, if (pnode == NULL) { return; }// if pnode not null, else if (pnode != NULL) {// pnode is different NULL displayTree(pnode->left); printf(" %d ", pnode->value); displayTree(pnode->right); } }
void FileSystem::displayTree(int indent, NodeInfo* node) { int tabspace = 2; vector<NodeInfo*>::iterator it; vector<NodeInfo*> cnodes; // Insert tabs before print cout << string(indent*tabspace,' '); if ( node->isStarred() ) { cout << "[~" << node->getName() << "~]" << endl; node->isStarred(false); } else { cout << "[" << node->getName() << "]" << endl; } // Increase indent ++indent; cnodes = node->getChildren(); for(it = cnodes.begin(); it != cnodes.end(); ++it) { if( (*it)->isDir() ) { displayTree(indent, (*it)); } else { //cout << string(" ",indent*tabspace) << (*it)->getName() << endl; cout << string(indent*tabspace,' '); if ( (*it)->isStarred() ) { cout << "~" << (*it)->getName() << "~" << endl; (*it)->isStarred(false); } else { cout << (*it)->getName() << endl; } } } }
void FileSystem::displayResults() { vector<DirInfo*>::iterator it; DirInfo* dir; cout << "Directory Tree: " << endl; displayTree(0,this->root); for(it = allDirs.begin(); it != allDirs.end(); ++it) { dir = (*it); if( dir->getNumSimilar() > 0 ) { dir->printInfo(); /* // Marks for diplicate listing dir->isStarred(true); displayTree(0,this->root); // Un-Marks in case of no diplicate listing dir->isStarred(false); */ } } }
int main() { int i; int times; //NodeType dynamicNum[] = {1, 3, 0, 3, 5, 3, 8, 1, 6, 9, 4}; // NodeType callNum[][CALL_NUM_LENGHT] = // { // {1, 3, 3, 3, 5, 3, 8, 1, 6, 9, 4}, // {1, 3, 3, 3, 5, 3, 8, 1, 6, 9, 7}, // {1, 3, 3, 3, 5, 3, 8, 1, 6, 8, 4}, // {1, 3, 3, 3, 5, 3, 8, 1, 6, 8, 5}, // {1, 3, 3, 3, 5, 3, 8, 1, 5, 3, 5}, // {1, 3, 3, 3, 5, 3, 8, 1, 5, 2, 5}, // // {1, 2, 3, 3, 5, 3, 8, 1, 6, 9, 4}, // {1, 2, 4, 3, 5, 3, 8, 1, 6, 9, 7}, // {1, 5, 3, 3, 5, 3, 8, 1, 6, 8, 4}, // {1, 4, 3, 3, 5, 3, 8, 1, 6, 8, 5}, // {1, 8, 3, 3, 5, 3, 8, 1, 5, 3, 5}, // {1, 9, 3, 3, 5, 3, 8, 1, 5, 2, 5}, // }; NodeType dynamicNum[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; NodeType dynamicNumC[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //times = GetTickCount(); Tree *pTree; pTree = createTree(); for (i=0; i<TIMES_COUNT; i++) { BOOL ret; incCallNum(dynamicNum, sizeof(dynamicNum)); //printfCallNumber(dynamicNum, sizeof(dynamicNum)); ret = addCallNumber(pTree, dynamicNum, sizeof(dynamicNum)); if (ret == FALSE) printf("add node failed.\n"); } printf("del...\n"); //getchar(); for (i=0; i<TIMES_COUNT; i++) { delCallNumber(pTree, dynamicNum, sizeof(dynamicNum)); //printfCallNumber(dynamicNum, sizeof(dynamicNum)); decCallNum(dynamicNum, sizeof(dynamicNum)); } releaseTree(pTree); pTree = NULL; displayTree(pTree); printf("\n"); printf("ok\n"); getchar(); return 0; }
main() { char cmd; /* Command from user */ char c; Node * head; /* Head of the binary search tree */ head = NULL; /* Initialize the binary search tree to be empty */ printf("Welcome to the binary search tree!\n\n"); while(1) { printf("Commands \n"); printf(" (q) Quit\n"); printf(" (e) Insert an alphabet \n"); printf(" (d) Delete an alphabet \n"); printf(" (t) Display tree \n"); printf(" (i) List the nodes in in-order\n"); printf(" (p) List the nodes in post-order\n"); printf("Enter command: "); cmd = getchar(); while(getchar() != '\n'); /* get rid of extra characters from stdin */ if (cmd == 'q') return; /* Quit */ else if (cmd == 'e') insertNode(&head); else if (cmd == 'd') deleteNode(&head); /* This is incomplete */ else if (cmd == 't') displayTree(head); else if (cmd == 'i') { /* Display nodes in-order */ printf("\n"); printf("In-order list:"); listInOrder(head); printf("\n\n"); } else if (cmd == 'p') { printf("\n"); printf("Post-order list:"); /* You must implement display nodes post-order */ listPostOrder(head); printf("\n\n"); } else { printf("Invalid command, try again\n"); } } }
gererCategorie::gererCategorie(QWidget *parent) : QDialog(parent), ui(new Ui::gererCategorie) //sousCategorie(std::vector); { ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); ui->treeWidget->setSelectionMode(QAbstractItemView::MultiSelection); ui->treeWidget->setDragEnabled(true); ui->treeWidget->viewport()->setAcceptDrops(true); ui->treeWidget->setDropIndicatorShown(true); ui->treeWidget->setDragDropMode(QAbstractItemView::InternalMove); // Set the number of columns in the tree ui->treeWidget->setColumnCount(2); QObject::connect(ui->Valider,SIGNAL(clicked()),this,SLOT(validerTree())); displayTree(); }
PassRefPtrWillBeRawPtr<VTTCueBox> VTTCue::getDisplayTree(const IntSize& videoSize) { RefPtrWillBeRawPtr<VTTCueBox> displayTree(ensureDisplayTree()); if (!m_displayTreeShouldChange || !track()->isRendered()) return displayTree.release(); // 10.1 - 10.10 calculateDisplayParameters(); // 10.11. Apply the terms of the CSS specifications to nodes within the // following constraints, thus obtaining a set of CSS boxes positioned // relative to an initial containing block: displayTree->removeChildren(); // The document tree is the tree of WebVTT Node Objects rooted at nodes. // The children of the nodes must be wrapped in an anonymous box whose // 'display' property has the value 'inline'. This is the WebVTT cue // background box. // Note: This is contained by default in m_cueBackgroundBox. m_cueBackgroundBox->setShadowPseudoId(cueShadowPseudoId()); displayTree->appendChild(m_cueBackgroundBox); // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not // WebVTT Ruby Text Objects must be wrapped in anonymous boxes whose // 'display' property has the value 'ruby-base'. // FIXME(BUG 79916): Text runs must be wrapped according to the CSS // line-wrapping rules, except that additionally, regardless of the value of // the 'white-space' property, lines must be wrapped at the edge of their // containing blocks, even if doing so requires splitting a word where there // is no line breaking opportunity. (Thus, normally text wraps as needed, // but if there is a particularly long word, it does not overflow as it // normally would in CSS, it is instead forcibly wrapped at the box's edge.) displayTree->applyCSSProperties(videoSize); m_displayTreeShouldChange = false; // 10.15. Let cue's text track cue display state have the CSS boxes in // boxes. return displayTree.release(); }
int main(void) { int chMenu, chElement, value, addValue, find; node *pRootNode = NULL; do { printf("\n\tBINARY TREE\n"); printf("\n1) Create binary tree\n"); printf("2) List binary tree\n"); printf("3) Delete binary tree\n"); printf("4) Total node \n"); printf("5) List tree with values \n"); printf("6) Insert value\n"); printf("7) Find value\n"); printf("\nENTRER VOTRE CHOIX : "); scanf("%d", &chMenu); printf("\n"); switch (chMenu) { case 1:{ chElement = 1; while (chElement != 0) { printf("Entrer la valeur pour l'inserer dans l'arbre:\n"); scanf("%d", &value);// addNode(&pRootNode,value); // on appel addnode avec comme parametre l'adresse de pRootNode, et la valeur printf("Voulez vous ajoutez un element? (1 / 0)\n"); scanf("%d", &chElement); } printf("\n"); break; } case 2:{ printf("\n**Display**\n"); displayTree(pRootNode);// l'adresse de pRootNode break; } case 3:{ printf("Delete Tree\n"); deleteTree(pRootNode); break; } case 4:{ int nb = numberNode(pRootNode); printf("Number of node : %d\n", nb); break; } case 5:{ printf("List with values \n"); displayTreeWith(pRootNode); break; } case 6 : { printf("Insert value"); scanf("%d",&addValue); printf("%d",addValue); insert(pRootNode,addValue); break; } case 7 : { printf("Find values\n"); scanf("%d",&find); findNode(pRootNode,find); break; } } } while (chMenu != 0); return 1; }
Node * Astar::startSearch(Pose start,double targetCov, int coord) { int ID = 1; int NodesExpanded = 0; if(this->tree.size() > 0) this->tree.clear(); if(!openList) { openList = new LList; } if(!closedList) { closedList = new LList; } // Be sure that open and closed lists are empty openList->free(); closedList->free(); if (!this->search_space) // Make sure that we have a map to search { // LOG(Logger::Warning,"Read the map and generate SearchSpace before Searching !!!") return NULL; } this->start.p.position.x = start.p.position.x; this->start.p.position.y = start.p.position.y; this->start.p.position.z = start.p.position.z; this->start.p.orientation.x = start.p.orientation.x; this->start.p.orientation.y = start.p.orientation.y; this->start.p.orientation.z = start.p.orientation.z; this->start.p.orientation.w = start.p.orientation.w; this->targetCov = targetCov; std::cout<<"\n --->>> Search Started <<<---"; findRoot(); // std::cout<<"\n"<<QString(" ---->>>Target is Set to be X=%1 Y=%2 Z=%3<<<---").arg(end.p.position.x).arg(end.p.position.y).arg(end.p.position.z).toStdString(); openList->add(root); // add the root to OpenList // while openList is not empty int count = 0; ros::Time search_begin = ros::Time::now(); while (openList->Start != NULL) { if((count++%1) == 0) { displayTree(); } current = openList->getHead(); // Get the node with the highest cost (first node) (it was the cheapest one before since we were taking the lower cost but now it is converted to a reward function) openList->next(); // Move to the next Node NodesExpanded++; // We reached the target pose, so build the path and return it. ros::Time reached_check_begin = ros::Time::now(); if (surfaceCoverageReached(current) && current!= root)//change goalReached to surfaceCoverageReached { // build the complete path to return // qDebug("Last Node destination: %f %f",current->pose.p.x(),current->pose.p.y()); current->next = NULL;//the last node in the path covFilteredCloud->points = current->cloud_filtered->points; //getting the accumelated cloud to check the coverage and display it in the test code std::cout<<"*************commulative distance : "<<current->distance<<"************ \n"; std::cout<<"*************commulative coverage : "<<current->coverage<<"************ \n"; std::cout<<"\n"<<QString(" --->>> Goal state reached with :%1 nodes created and :%2 nodes expanded <<<---").arg(ID).arg(NodesExpanded).toStdString(); // qDebug(" --->>> General Clean UP <<<---"); fflush(stdout); // int m=0; // while (p != NULL) // { // cout<<"\n --->>> Step["<<++m<<"] X="<<p->pose.p.x()<<" Y="<<p->pose.p.y(); // //cout<<"\n --->>> Angle is="<<RTOD(p->angle); // fflush(stdout); // p = p->parent; // } // Going up to the Root p = current; path = NULL; while (p != NULL) { // cout<<"\n Am Still HERE Step["<<++m<<"] X="<<p->pose.x<<" Y="<<p->pose.y; // fflush(stdout); // remove the parent node from the closed list (where it has to be) if(p->prev != NULL) (p->prev)->next = p->next; if(p->next != NULL) (p->next)->prev = p->prev; // check if we're removing the top of the list if(p == closedList->Start) closedList->next(); // set it up in the path p->next = path; path = p; p = p->parent; } // now delete all nodes on OPEN and Closed Lists openList->free(); closedList->free(); return path; } ros::Time reached_check_end = ros::Time::now(); double check_elapsed = reached_check_end.toSec() - reached_check_begin.toSec(); std::cout<<"surface coverage check duration: "<< check_elapsed <<"\n"; // Create List of Children for the current NODE if(!(childList = makeChildrenNodes(current))) // No more Children => Search Ended Unsuccessfully at this path Branch { std::cout<<"\n --->>> Search Ended On this Branch / We Reached a DEAD END <<<---"; } ros::Time make_children_end = ros::Time::now(); double make_elapsed = make_children_end.toSec() - reached_check_end.toSec(); std::cout<<"make children duration: "<< make_elapsed <<"\n"; // insert the children into the OPEN list according to their f values ros::Time childrentest_begin = ros::Time::now(); std::cout<<" <<<<<<<<<<<<<<<<<<<<<<<<<<<< new children SET >>>>>>>>>>>>>\n"; while (childList != NULL) { ros::Time childtest_begin = ros::Time::now(); curChild = childList; childList = childList->next; // set up the rest of the child node details curChild->parent = current; curChild->depth = current->depth + 1; curChild->id = ID++; curChild->next = NULL; curChild->prev = NULL; //************displaying the tested child point*********** // std::vector<geometry_msgs::Point> pts; // geometry_msgs::Point pt; // pt.x = curChild->pose.p.position.x; pt.y = curChild->pose.p.position.y; pt.z = curChild->pose.p.position.z; // pts.push_back(pt); // visualization_msgs::Marker ptsList = drawPoints(pts,2,1000000000); // testPointPub.publish(ptsList); //************voxelgrid*********** ros::Time all_begin = ros::Time::now(); pcl::PointCloud<pcl::PointXYZ>::Ptr tempCloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ> temp_cloud, collective_cloud; ros::Time extract_begin = ros::Time::now(); temp_cloud = obj->extractVisibleSurface(curChild->senPose.p); ros::Time extract_end = ros::Time::now(); double extract_elapsed = extract_end.toSec() - extract_begin.toSec(); std::cout<<"Extract visible surface duration: "<< extract_elapsed <<"\n"; collective_cloud.points = curChild->parent->cloud_filtered->points; // std::cout<<"Parent cloud size: "<<collective_cloud.size()<<"\n"; // std::cout<<"child cloud size: "<<temp_cloud.size()<<"\n"; collective_cloud +=temp_cloud; // std::cout<<"collective cloud size: "<<collective_cloud.size()<<"\n"; tempCloud->points = collective_cloud.points; ros::Time filtering_begin = ros::Time::now(); pcl::VoxelGrid<pcl::PointXYZ> voxelgrid; voxelgrid.setInputCloud (tempCloud); voxelgrid.setLeafSize (0.5f, 0.5f, 0.5f); voxelgrid.filter (*curChild->cloud_filtered); ros::Time filtering_end = ros::Time::now(); double filtering_elapsed = filtering_end.toSec() - filtering_begin.toSec(); std::cout<<"filtering duration: "<< filtering_elapsed <<"\n"; // std::cout<<"\nchild collective cloud after filtering size: "<<curChild->cloud_filtered->size()<<"\n"; ros::Time calc_begin = ros::Time::now(); curChild->coverage = obj->calcCoveragePercent(curChild->cloud_filtered); ros::Time calc_end = ros::Time::now(); double calc_elapsed = calc_end.toSec() - calc_begin.toSec(); std::cout<<"calculate percentage duration: "<< calc_elapsed <<"\n"; ros::Time all_end = ros::Time::now(); double all_elapsed = all_end.toSec() - all_begin.toSec(); std::cout<<"all the part duration: "<< all_elapsed <<"\n\n"; curChild->distance = curChild->parent->distance + Dist(curChild->pose.p,curChild->parent->pose.p); // curChild->g_value = heuristic->gCost(curChild); curChild->h_value = heuristic->hCost(curChild); curChild->f_value = curChild->h_value;//curChild->g_value + curChild->h_value; Node * p; // check if the child is already in the open list // std::cout<<" OPEN LIST NODES\n"<<std::endl; // openList->print(); if (debug == true) { std::cout<<"curChildren f value= "<<curChild->f_value<<"\n"; std::cout<<"\n Finding the curchild : "<<curChild->pose.p.position.x<<" "<< curChild->pose.p.position.y<<" "<<curChild->pose.p.position.z<<" "<<curChild->pose.p.orientation.x<<" "<<curChild->pose.p.orientation.y<<" "<<curChild->pose.p.orientation.z<<" "<<curChild->pose.p.orientation.w<< std::endl; } if( (p = openList->find(curChild))) { if (debug == true) std::cout<<"check if the child is already in the open list"<<"\n"; if (p->f_value >=curChild->f_value)// it was <= (to take least cost) but now it is changed to be reward function && (p->direction == curChild->direction)) { if (debug == true) std::cout<<"Free the node the openlist check"<<"\n"; freeNode(curChild); curChild = NULL; } // the child is a shorter path to this point, delete p from the closed list else if (p->f_value < curChild->f_value )//&& (p->direction == curChild->direction))//************IMPORTANT****************** { if (debug == true) std::cout<<"removing the p from the openlist"<<"\n"; openList->remove(p); // std::cout<<"*****SELECTED child h value: "<<curChild->f_value<<"********\n"; // std::cout<<"parent :"<<"position x:"<<curChild->pose.p.position.x<<" y:"<<curChild->pose.p.position.y<<" z:"<<curChild->pose.p.position.z<<"\n"; // std::cout<<"parent :"<<"orientation x:"<<curChild->pose.p.orientation.x<<" y:"<<curChild->pose.p.orientation.y<<" z:"<<curChild->pose.p.orientation.z<<" w:"<<curChild->pose.p.orientation.w<<"\n"; //cout<<"\n --->>> Opened list -- Node is deleted, current child X="<<curChild->pose.x<<" Y="<<curChild->pose.y<<" has shorter path<<<---"; fflush(stdout); } } // test whether the child is in the closed list (already been there) if (curChild) { if (debug == true) { std::cout<<" check if the current child in the closed list\n"<<std::endl; std::cout<<" CLOSED LIST NODES\n"<<std::endl; closedList->print(); std::cout<<" Finding the curchild : "<<curChild->pose.p.position.x<<" "<< curChild->pose.p.position.y<<" "<<curChild->pose.p.position.z<<" "<<curChild->pose.p.orientation.x<<" "<<curChild->pose.p.orientation.y<<" "<<curChild->pose.p.orientation.z<<" "<<curChild->pose.p.orientation.w<< std::endl; } if((p = closedList->find(curChild))) { if (debug == true) std::cout<<"the child is already in the closed list"<<"\n"; if (p->f_value >=curChild->f_value)// && p->direction == curChild->direction)//************IMPORTANT****************** { if (debug == true) std::cout<<"Free the node the closed list check, parent is bigger than the child"<<"\n"; freeNode(curChild); curChild = NULL; } // the child is a shorter path to this point, delete p from the closed list else { if (debug == true) std::cout<<"the parent f value is less than the child"<<"\n"; /* This is the tricky part, it rarely happens, but in my case it happenes all the time :s * Anyways, we are here cause we found a better path to a node that we already visited, we will have to * Update the cost of that node and ALL ITS DESCENDENTS because their cost is parent dependent ;) * Another Solution is simply to comment everything and do nothing, doing this, the child will be added to the * Open List and it will be investigated further later on. */ //TODO : this SHOULD be fixed, very very DODGY // Node *ptr = closedList->Start; // while(ptr) // { // if(ptr->parent == p) // ptr->parent = NULL; // ptr = ptr->next; // } // closedList->Remove(p); //cout<<"\n --->>> Closed list -- Node is deleted, current child X="<<curChild->pose.x<<" Y="<<curChild->pose.y<<" has shorter path<<<---"; fflush(stdout); } } if (debug == true) std::cout<<"DID NOT find the child in the closed list\n"; } ros::Time current_end = ros::Time::now(); double current_elapsed = current_end.toSec() - search_begin.toSec(); if (debug == true) { std::cout<<"\n\n\n#####################################################################################\n"; std::cout<<"#################Duration of the SEARCH till now (s)= "<<current_elapsed<<"####################\n\n\n"; } // ADD the child to the OPEN List if (curChild) { if (debug == true) std::cout<<"adding the cur child to the openlist"<<"\n"; openList->add(curChild); } ros::Time childtest_end = ros::Time::now(); double childtest_elapsed = childtest_end.toSec() - childtest_begin.toSec(); if (debug == true) std::cout<<"****Child Test duration (s)= "<<childtest_elapsed<<"****\n"; } ros::Time childrentest_end = ros::Time::now(); double childrentest_elapsed = childrentest_end.toSec() - childrentest_begin.toSec(); // if (debug == true) std::cout<<"****Children Test duration (s) of node "<<current->id<<"= "<<childrentest_elapsed<<"****\n\n\n"; ros::Time search_end = ros::Time::now(); double current_elapsed1 = search_end.toSec() - search_begin.toSec(); if (debug == true) { std::cout<<"\n\n\n\n******************************************************************************************\n"; std::cout<<"*********************SEARCH DURATION (s)= "<<current_elapsed1<<"*****************\n\n\n\n"; } // put the current node onto the closed list, ==>> already visited List closedList->add(current); // Test to see if we have expanded too many nodes without a solution if (current->id > this->MAXNODES) { // LOG(Logger::Info,QString(" --->>> Expanded %d Nodes which is more than the maximum allowed MAXNODE=%1 , Search Terminated").arg(current->id,MAXNODES)) //Delete Nodes in Open and Closed Lists std::cout<<"the closed list and open list is freed"<<"\n"; closedList->free(); openList->free(); path = NULL; return path; // Expanded more than the maximium nodes state } } //... end of OPEN loop /* if we got here, then there is no path to the goal * delete all nodes on CLOSED since OPEN is now empty */ if (debug == true) std::cout<<"counter for displaying the tree: "<<count<<" \n"; closedList->free(); std::cout<<"\n --->>>No Path Found<<<---"; return NULL; }
// Prints out a tree. The tree is displayed horizontally; its root is at the left, // with its branches spreading out to the right (up, on the screen) and left (down, // on the screen). Provided for you; do not modify. void printTree(Tree* root) { displayTree(root, 0); }
void main() { char menu[LINES][STR_SIZE] = {"Add", "Delete", "search", "Display All", "Display Root", "Exit"}; char key; int current = 0, i = 0, item, preItem; BSTNode *tree = NULL; do { clrscr(); for (i = 0; i < LINES; i++) { if (current == i) { textcolor(CYAN + BLINK); cprintf("\r%s\n", menu[i]); } else { textcolor(WHITE); cprintf("\r%s\n", menu[i]); } } key = getch(); if (!key) key = getch(); switch (key) { case UP: current = (current + LINES - 1) % LINES; break; case DOWN: current = ++current % LINES; break; case END: current = LINES - 1; break; case HOME: current = 0; break; case ENTER: clrscr(); textcolor(WHITE); switch (current) { case 0: printf("Please enter an integer to add: "); scanf("%d", &item); insertNode(&tree, item); break; case 1: printf("Please give me node to delete: "); scanf("%d", &item); removeNode(tree, item); break; case 2: printf("Please enter an integer to search for: "); scanf("%d", &item); if (findNode(tree, item)) printf("Found!\n"); else printf("Not Found!\n"); break; case 3: displayTree(tree); break; case 4: displayRoot(tree); break; case 5: printf("GOOD BYE"); break; } getch(); break; } } while (current != (LINES - 1) || key != ENTER); }
int main(int argc, char **argv) { FILE *in = NULL; int num_read, array_size = 0; if(argc != 2){ printf("hw4 <input-file>\n"); return 1; } in = fopen(argv[1], "r"); if(in == NULL){ printf("File can not be opened.\n"); return 2; } // declare the array int array[MAX_SIZE]; // read from the second line to get each element of the array while(!feof(in)){ fscanf(in, "%d", &num_read); if(isValidID(array, array_size, num_read) == 0) { array[array_size] = num_read; array_size++; printf("%d added to array\n", num_read); } else if(isValidID(array, array_size, num_read) == 1) { printf("ERROR - %d bad ID. Not in range [0, 99].\n", num_read); } else if(isValidID(array, array_size, num_read) == 2) { printf("ERROR - %d bad ID. Duplicate.\n", num_read); } } fclose(in); Node *root1 = NULL, *root2 = NULL, *root3 = NULL; int i; // task1: construct a bst from the unsorted array printf("=== task1: construct a bst from the unsorted array ===\n"); for (i = 0; i < array_size; i++) { root1 = bstInsert(root1, array[i]); } displayTree(root1, 0); printf("Height of bst1 is %d\n", getBstHeight(root1)); // task2: sort the array and use the sorted array to construct a bst, each time taking an element in order printf("=== task2: sort the array and use the sorted array to construct a bst ===\n"); bsort1(array, array_size); for (i = 0; i < array_size; i++) { root2 = bstInsert(root2, array[i]); } displayTree(root2, 0); printf("Height of bst2 is %d\n", getBstHeight(root2)); // task3: use the sorted array to construct a balanced bst printf("=== task3: use the sorted array to construct a balanced bst ===\n"); root3 = sortedArrayToBalancedBst(array, 0, array_size-1); displayTree(root3, 0); printf("Height of bst3 is %d\n", getBstHeight(root3)); return 0; }