根据中序和后序遍历序列求层序遍历序列

来源:互联网 发布:道教里的仙人 知乎 编辑:程序博客网 时间:2024/06/14 15:28


如题,顺便还求了一下树的高度。

#include <iostream>#include <queue>#include <math.h>using namespace std;struct Node{    Node *lchild;    Node *rchild;    char c;};void preOrder(Node *T){    cout << T->c;    if (T->lchild != NULL)    {        preOrder(T->lchild);    }    if (T->rchild != NULL)    {        preOrder(T->rchild);    }}void levelOrder(Node *T){    queue<Node*> q;    q.push(T);    Node *temp;    while (!q.empty())    {        temp = q.front();        q.pop();        cout << temp->c;        if (temp->lchild != NULL)        {            q.push(temp->lchild);        }        if (temp->rchild != NULL)        {            q.push(temp->rchild);        }    }}Node Tree[100];int local;string str1,str2;Node* creat(){    Tree[local].lchild = Tree[local].rchild = NULL;    local++;    return &Tree[local-1];}Node* build(int s1,int e1,int s2,int e2){    Node *rec = creat();    rec->c = str2[e2];    int id = str1.find(str2[e2]);    if (id != s1)    {        rec->lchild = build(s1,id-1,s2,s2+(id-s1)-1);    }    if (id != e1)    {        rec->rchild = build(id+1,e1,s2+(id-s1),e2-1);    }    return rec;}int find_high(Node *T){    if (T == NULL) return 0;    else        return max(find_high(T->lchild),find_high(T->rchild))+1;}int main(){    cin >> str1 >> str2;    local = 0;    int len1 = str1.size();    int len2 = str2.size();    Node *T = NULL;    T = build(0,len1-1,0,len2-1);    preOrder(T);    cout << endl;    levelOrder(T);    cout << endl;    cout << find_high(T) << endl;}


0 0
原创粉丝点击