DS二叉树–二叉树构建与遍历

  • Post author:
  • Post category:其他


样例输入

2

AB0C00D00

AB00C00

样例输出

ABCD

BCAD

CBDA

ABC

BAC

BCA

#include <string>
#include <string.h>
#include <iostream>
using namespace std;
 
class Node
{
public:
    char data;
    Node *left, *right;
    Node(){}
    ~Node()
    {
        delete left;
        delete right;
    }
};
void pre(Node *tree)
{
    if(tree)
    {
        cout << tree->data;
        pre(tree->left);
        pre(tree->right);
    }
}
void in(Node *tree)
{
    if(tree)
    {
        in(tree->left);
        cout << tree->data;
        in(tree->right);
    }
}
void post(Node *tree)
{
    if(tree)
    {
        post(tree->left);
        post(tree->right);
        cout << tree->data;
    }
}
 
static int i = 0;
Node *creattree(string str)
{
    Node *p = new Node;
    if(str[i] == '0')
    {
        p = NULL;
    }
    else
    {
        p->data = str[i];
        i++;
        p->left = creattree(str);
        i++;
        p->right = creattree(str);
    }
    return p;
}
 
int main()
{
    int T;
    string str;
    cin >> T;
    while(T--)
    {
        i = 0;
        Node *tree;
        cin >> str;
        tree = creattree(str);
        pre(tree);
        cout << endl;
        in(tree);
        cout << endl;
        post(tree);
        cout << endl;
        delete tree;
    }
    return 0;
}



版权声明:本文为Littlsecr原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。