PTA: Preorder sequence creates a binary tree

topic

Write a program to read a pre-order traversal string input by the user, and build a binary tree (stored as a binary linked list) based on this string. For example, the following preorder traversal string: ABC##DE#G##F### where "#" represents a space, representing an empty tree. Then perform an in-order traversal of the binary tree and output the traversal results.

Input format

Multiple sets of test data, each set of test data has one line. The line has only one string and the length does not exceed 100.

Output format

For each set of data,
outputs the sequence of in-order traversal of the binary tree, with a space after each character.
Each group outputs one line, corresponding to one line of input string.

Input examples (and their corresponding binary trees)

abc##de#g##f###
Insert image description here

Output sample

c b e g d f a

code

#include<iostream>
#include<string>
using namespace std;

typedef struct treenode
{
    
    
    char val;
    struct treenode* left;
    struct treenode* right;
}treenode;


treenode* createnode(char a)
{
    
    
    treenode* newnode = new treenode;
    if (newnode == nullptr)
        return nullptr;
    newnode->left = nullptr;
    newnode->right = nullptr;
    newnode->val = a;
    return newnode;
}

treenode* createtree(string a, int* index)
{
    
    
    treenode* head = nullptr;
    if ((*index) < a.size() && a[*index] != '#')
    {
    
    

        head = createnode(a[*index]);
        ++(*index);
        head->left = createtree(a, index);
        ++(*index);
        head->right = createtree(a, index);
    }
    return head;
}
void inderoder(treenode* head)
{
    
    
    if (nullptr == head)
    {
    
    
        return;
    }
    inderoder(head->left);
    cout << head->val << " ";
    inderoder(head->right);
}
int main()
{
    
    
    string s;
    while (cin >> s)
    {
    
    
        int index = 0;
        treenode* head = createtree(s, &index);
        inderoder(head);
        cout << endl;
    }
}

Guess you like

Origin blog.csdn.net/m0_74195626/article/details/134121007