1 广搜存在问题!!!!! 2 //建立一棵树,然后做深搜,广搜 3 #include <iostream> 4 5 typedef struct node{ 6 int data; 7 struct node* left; 8 struct node* right; 9 }; 10 11 struct node* new_node(int _data) 12 { 13 node* temp = (node*)malloc(sizeof(node)); 14 if(!temp) 15 { 16 printf("新建节点失败"); 17 exit(1); 18 } 19 temp->data = _data; 20 temp->left = NULL; 21 temp->right = NULL; 22 return temp; 23 } 24 25 //递归 26 void deep(node *r) 27 { 28 printf("%d ",r->data); 29 if(r->left) 30 { 31 deep(r->left); 32 } 33 34 if(r->right) 35 deep(r->right); 36 } 37 //写一个队列,有入队列,出队列的操作 38 typedef struct queuenode 39 { 40 node* _node; 41 queuenode* next; 42 }; 43 typedef struct queue 44 { 45 queuenode * front; 46 queuenode *rear; 47 }myqueue; 48 49 myqueue _queue; 50 //原来,结构体中含有结构体的是这样初始化的 51 queuenode* new_queuenode() 52 { 53 queuenode *t = (queuenode*)malloc(sizeof(queuenode)); 54 t->next = NULL; 55 node *tt = new_node(0); 56 t->_node = tt; 57 return t; 58 } 59 60 void push(node *t) 61 { 62 queuenode *tt = new_queuenode(); 63 tt->_node = t; 64 _queue.front = tt; 65 _queue.front = tt->next; 66 return; 67 } 68 bool isEmpty() 69 { 70 if(_queue.front ==_queue.rear) 71 return 1; 72 else 73 return 0; 74 75 } 76 node* pop() 77 { 78 queuenode *tt = new_queuenode(); 79 tt = _queue.rear; 80 _queue.rear = _queue.rear->next; 81 82 node *t = new_node(0); 83 t = tt->_node; 84 //free(tt); 85 return t; 86 } 87 88 void broad(node *r) 89 { 90 queuenode *t = new_queuenode(); 91 _queue.front = _queue.rear = t; 92 node* aa = r->left; 93 r->right; 94 //初始化队列 95 push(r); 96 node *tempnode = new_node(0); 97 node *l = new_node(0); 98 node *rr = new_node(0); 99 while(!isEmpty()) 100 { 101 tempnode = pop(); 102 printf("%d ",tempnode->data); 103 l = tempnode->left; 104 push(l); 105 rr = tempnode->right; 106 push(rr); 107 // free(tempnode); 108 } 109 return; 110 } 111 int main() 112 { 113 //建树 114 node* root = new_node(0); 115 node *n1 = new_node(1); 116 node *n2 = new_node(2); 117 node *n3 = new_node(3); 118 node *n4 = new_node(4); 119 node *n5 = new_node(5); 120 node *n6 = new_node(6); 121 node *n7 = new_node(7); 122 root->left = n1; 123 root->right = n2; 124 n1->left = n3; 125 n1->right = n4; 126 n2->left = n5; 127 n2->right = n6; 128 n3->left = n7; 129 130 //深度优先 递归 131 //deep(root); 132 broad(root); 133 134 return 0; 135 }