p = (Arc *)malloc(sizeof(Arc)) ; scanf_s(\ p->next = v2-1 , p->weight = w ; p->nextArc = G.ver[v1-1].firstArc ; G.ver[v1-1].firstArc = p ; q = (Arc *)malloc(sizeof(Arc)) ; q->next = v1-1 , q->weight = w ; q->nextArc = G.ver[v2-1].firstArc ; G.ver[v2-1].firstArc = q ; } }
void DFS(Graph &G , int v) { Arc * p ; printf(\v+1) ; visited[v] = 1; p = G.ver[v].firstArc ; while(p) { if(!visited[p->next]) DFS(G,p->next) ; p = p->nextArc ; } }
void DFSTra(Graph &G) { for(int i = 0 ; i < G.nnum ; i++) visited[i] = 0 ;
for(int i = 0;i void BFSTra(Graph &G) { LinkQueue Q ; InitQueue(Q) ; for(int i = 0 ; i < G.nnum ; i++) visited[i] = 0 ; for(int i = 0 ; i< G.nnum ; i++) { if(!visited[i]) { EnQueue(Q,i); visited[i] = 1 ; while(!QueueEmp(Q)) { int u ; DeQueue(Q,u) ; printf(\ for(Arc * a = G.ver[u].firstArc ; a!=NULL ; a = a->nextArc) if(!visited[a->next]){ EnQueue(Q,a->next); visited[a->next] = 1 ; } } } } } int main() { Graph G ; Create(G) ; printf(\深度优先搜索:\\n\ DFSTra(G) ; printf(\广度优先搜索:\\n\ BFSTra(G) ; system(\ return 0; } 查找 设计一个读入一串整数构成一颗二叉排序树的程序,从二叉排序树中删除一个结点,使该二叉树仍保持二叉排序树的特性。 #include \ #include \ #include \ typedef struct tree { struct tree *left; struct tree *right; int key; } BSTNode , * BSTree; void insertBST(BSTree &T,int key) { } void createBST(BSTree &t) { } void InOrder(BSTree t) { BSTree p = t; int key; printf(\请输入第一个结点的值(0表示结束):\\n\) ; scanf_s(\,&key); while(key != 0) { } insertBST(t , key); printf(\请输入下一个结点的值(0表示结束):\\n\) ; scanf_s(\ , &key); BSTree f = NULL , p = T; while(p) { } p = (BSTree)malloc(sizeof(BSTNode)); p->key = key ; p->left = p->right = NULL; if(T == NULL) { } if(key < f->key) f->left = p; f->right = p; else T = p; else if(p->key == key) return ; f = p; if(key < p->key) p = p->left ; p = p->right ; else } if(p != NULL) { } InOrder(p->left); printf(\中序遍历当前二叉树:\\n\) ; printf(\,p->key ); InOrder(p->right ); int searchBST(BSTree t , int key) { } BSTree deleteBST(BSTree T , int key) { BSTree p,tmp,parent = NULL; p = T; while(p) { if(p->key == key) break; parent = p; if(key < p->key) p = p->left ; p = p->right ; else if(key == t->key) return 1; return 0; return searchBST(t->left , key); return searchBST(t->right , key); if(t==NULL) if(key } if(!p) return NULL; tmp=p; if(!p->right&&!p->left) { if(!parent) T = NULL; else if(p == parent->right) parent->right = NULL; else parent->left = NULL; free(p); } else if(!p->right) { p = p->left; if(!parent) T = p; else if(tmp == parent->left) parent->left = p; else parent->right = p; free(tmp); } else if(!p->left) { p = p->right; if(!parent) T = p; else if(tmp == parent->left) parent->left = p ; else parent->right = p; free(tmp); } else if(p->right&&p->left) { parent = p; p = p->right; while(p->left) { parent = p; p = p->left; } tmp->key = p->key; if(p == parent->left) parent->left = NULL; else parent->right = NULL; free(p); } } return T;