1. 程式人生 > >樹的遞迴與非遞迴遍歷(C++讀檔案)

樹的遞迴與非遞迴遍歷(C++讀檔案)

從“tree.in”檔案裡讀取字串,構造樹,若遇到’0’,則認為是空樹,然後對該樹進行四種遍歷

#include <iostream>
#include <stack>
#include <queue>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;

#define ElemType char

typedef struct treeNode {
    struct treeNode * lchild;
    struct
treeNode * rchild; ElemType data; }treeNode,* tree; void createTree(tree & t, string str) { static int N = 0; if (str.length() <= N) return; ElemType ch = str[N++]; if (ch == '0') t = NULL; else { t = (treeNode*)malloc(sizeof(treeNode)); t->data = ch; createTree(t->lchild, str); createTree(t->rchild, str); } } //遞迴前中後序
void preOrder(tree & t) { if (t) { std::cout << t->data<<" "; preOrder(t->lchild); preOrder(t->rchild); } } void inOrder(tree & t) { if (t) { inOrder(t->lchild); std::cout << t->data<<" "; inOrder(t->rchild); } } void
postOrder(tree & t) { if (t) { postOrder(t->lchild); postOrder(t->rchild); std::cout << t->data<<" "; } } void levelOrder(tree & t) { queue<tree> q; if (t) { q.push(t); while (!q.empty()) { tree temp = q.front(); cout << temp->data << " "; q.pop(); if (temp->lchild) q.push(temp->lchild); if (temp->rchild) q.push(temp->rchild); } } } //非遞迴前中後序 void preOrder2(tree &t) { stack<treeNode *> s; while (!s.empty() || t) { if (t) { cout << t->data; s.push(t); t = t->lchild; } else { t=s.top(); s.pop(); t = t->rchild; } } } void inOrder2(tree &t) { stack<treeNode *> s; while (!s.empty ()|| t) { if (t) { s.push(t); t = t->lchild; } else { t = s.top(); s.pop(); cout << t->data; t = t->rchild; } } } void postOrder2(tree & t) { stack<treeNode*> s; treeNode * r = NULL; //輔助指標,指向其最近訪問過的結點 while (!s.empty ()|| t) { if (t) { s.push(t); t = t->lchild; } else { t = s.top(); if (t->rchild&&t->rchild != r) { t = t->rchild; s.push(t); t = t->lchild; } else { t = s.top(); s.pop(); cout << t->data; r = t; //當出棧的節點沒有右孩子或右孩子剛剛被訪問過時,訪問過它後,再出棧一個元素 t = NULL; } } } } int main() { ifstream ifs; ifs.open("tree.in"); string str; ifs >> str; cout << str << endl; tree t; createTree(t, str); preOrder(t); cout << endl; createTree(t, str); inOrder(t); cout << endl; createTree(t, str); postOrder(t); cout << endl; createTree(t, str); levelOrder(t); cout << endl; ifs.close(); system("PAUSE"); return EXIT_SUCCESS; }