欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

树的四种递归遍历(C++读文件)

程序员文章站 2022-06-24 20:25:33
从“tree.in”文件里读取字符串,构造树,若遇到’0’,则认为是空树,然后对该树进行四种遍历 #include #include #i...

从“tree.in”文件里读取字符串,构造树,若遇到’0’,则认为是空树,然后对该树进行四种遍历

#include 
#include 
#include 
#include 
#include 
#include 
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 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);
        }
    }
}
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;
}