【資料結構】二叉樹的前中後遍歷與層次遍歷(遞迴與非遞迴)
阿新 • • 發佈:2018-12-22
水一波作業
#include <iostream> #include <cstring> //#pragma GCC optimize(2) #include<time.h> #include <map> #include <queue> #include <stack> #include <cmath> #include <algorithm> using namespace std; #define maxn 1005 #define inf 1e18 #define eps 0.00001 typedef long long ll; const ll mod = 1e9+7; const double pi = acos(-1); typedef struct node { struct node *lchild; struct node *rchild; char date; }BiTreeNode,*BiTree; void create(BiTree &T) { char c; cin >> c; if(c == '#') T = NULL; else { T = new BiTreeNode; T ->date = c; create(T->lchild); create(T->rchild); } return ; } void Pre_recursion(BiTree T) { if(T) { cout << T->date << " "; Pre_recursion(T->lchild); Pre_recursion(T->rchild); } return ; } void Mid_recursion(BiTree T) { if(T) { Mid_recursion(T->lchild); cout << T->date << " "; Mid_recursion(T->rchild); } return ; } void Post_recursion(BiTree T) { if(T) { Post_recursion(T->lchild); Post_recursion(T->rchild); cout << T->date << " "; } return ; } void Mid_non_recursion(BiTree T) { stack<BiTree>S; BiTree p = T; BiTree q = new node; while( p || !S.empty() ) { if(p) { S.push(p); p = p->lchild; } else { q = S.top(); cout << q->date << " "; S.pop(); p = q->rchild; } } return ; } void Every(BiTree T) { queue<BiTree>S; BiTree p = T; BiTree q = new node; if(T) { S.push(T); while(!S.empty()) { q = S.front(); cout << q->date << " "; S.pop(); if(q->lchild) S.push(q->lchild); if(q->rchild) S.push(q->rchild); } } return ; } int main() { //ios::sync_with_stdio(false); //cin.tie(0);cout.tie(0); //freopen("D:\\test1.in","w",stdout); //srand((int)time(0)); BiTree T; create(T); cout << "二叉樹建立成功" << endl; cout << "遞迴版前序遍歷" << endl; Pre_recursion(T); cout << endl; cout << "遞迴版中序遍歷" << endl; Mid_recursion(T); cout << endl; cout << "遞迴版後序遍歷" << endl; Post_recursion(T); cout << endl; cout << "非遞迴版中序遍歷" << endl; Mid_non_recursion(T); cout << endl; cout << "層次遍歷" << endl; Every(T); cout << endl; return 0; }