C++ preorder string to create binary tree and inorder traversal

Topic description

Write a program that reads a string of preorder traversal strings input by the user, and builds a binary tree (stored as a pointer) based on this string. For example, the following preorder traversal string: ABC##DE#G##F### where "#" represents a space, and the space character represents an empty tree. After the binary tree is established, in-order traversal is performed on the binary tree, and the traversal result is output.

Enter description:

The input consists of a 1-line string with a length of no more than 100.

Output description:

There may be multiple sets of test data, for each set of data,
Output the sequence of inorder traversal of the input string after building a binary tree, with a space after each character.
Each output result occupies one line.
Example 1

enter

abc##de#g##f###

output

c b e g d f a 

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 101
 
struct Node{
    Node *lchild;
    Node *rchild;
    char c;
};
 
Node *CreateNode()//Create a new node and return the node pointer
{
    Node *ret=(Node*)malloc(sizeof(Node));
    ret->lchild=NULL;
    ret->rchild=NULL;
    return ret;
}
 
void InOrder(Node *T)//Inorder traversal
{
    if(T->lchild!=NULL)
		InOrder(T->lchild);
    printf("%c ", T->c);
    if(T->rchild!=NULL)
		InOrder(T->rchild);
}

void Del(Node *T)//Delete the tree
{
    if(T->lchild!=NULL)//Delete the left subtree
    {
        Del(T->lchild);
        T->lchild=NULL;
    }
    if(T->rchild!=NULL)//Delete the right subtree
    {
        Del(T->rchild);
        T->rchild=NULL;
    }
    free(T);//Delete the root node
}
 
unsigned pos;//Where is the marked string processed
char str[N];//The read string
 
Node *BuildTree()//Create a binary tree according to the string and return the root node pointer
{
    if(pos>=strlen(str))
		return NULL;//After the string is processed, just rest
    if(str[pos]=='#')//Create an empty tree, that is, return a null pointer
    {
        pos++;//Prepare to process the next character
        return NULL;
    }
    Node *p=CreateNode();//Create an empty node
    p->c=str[pos++];//Pre-order, get the character information of the root node first
    p->lchild=BuildTree();//Create left subtree
    p->rchild=BuildTree();//Create the right subtree
    return p;//Finish, return the root node pointer
}
 
intmain()
{
    while(gets(str))
    {
        pos=0;//Where is the mark string processed
        Node *T=BuildTree();//Build the entire tree according to the string
        InOrder(T);//Inorder traversal and output
        printf("\n");
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324848833&siteId=291194637