链表遍历算法
前序遍历
1 void PreOrder(struct Node *r) { 2 if(r==NULL) 3 return ; 4 stack<struct Node *> s; 5 s.push(r); 6 while(!s.empty()) 7 { 8 struct Node *cur = s.top(); 9 cout<<cur->data<<" "; 10 s.pop(); 11 if(cur->r!=NULL) 12 s.push(cur->r); 13 if(cur->l !=NULL) 14 s.push(cur->l); 15 } 16 cout<<endl; 17 }
中序遍历
1 void InOrder(struct Node *r) 2 { 3 if(r==NULL) 4 return ; 5 6 stack<struct Node *> s; 7 s.push(r); 8 struct Node *cur = r->l; 9 while(cur !=NULL || s.size()>0) 10 { 11 while(cur !=NULL) 12 { 13 s.push(cur); 14 cur = cur->l; 15 } 16 cur = s.top(); 17 s.pop(); 18 cout<<cur->data<<" "; 19 cur=cur->r; 20 } 21 cout<<endl; 22 }
后序遍历
1 void PostOrder(struct Node *r) 2 { 3 if(r==NULL) 4 return ; 5 struct Node *cur= r; 6 struct Node *pre = NULL; 7 stack<struct Node *> s; 8 while(cur !=NULL || s.size()>0) 9 { 10 while(cur !=NULL) 11 { 12 s.push(cur); 13 cur= cur->l; 14 } 15 cur = s.top(); 16 if(cur->r ==NULL || pre == cur->r) 17 { 18 cout<<cur->data<<" "; 19 s.pop(); 20 pre=cur; 21 cur=NULL; 22 } 23 else 24 cur = cur->r; 25 } 26 cout<<endl; 27 }
层次遍历
1 void LevelOrder(struct Node *r) 2 { 3 if(r==NULL) 4 return ; 5 queue<struct Node *> q; 6 q.push(r); 7 while(q.size()>0) 8 { 9 struct Node *cur = q.front(); 10 cout<<cur->data<<" "; 11 q.pop(); 12 if(cur->l!=NULL) 13 q.push(cur->l); 14 if(cur->r!=NULL) 15 q.push(cur->r); 16 } 17 cout<<endl; 18 }

浙公网安备 33010602011771号