Output the hierarchical traversal sequence swustoj of the binary tree created with preorder traversal

Output the hierarchical traversal sequence of the binary tree created with preorder traversal
 1000(ms)
 10000(kb)
 2315 / 4935
Use the preorder recursive traversal algorithm to create a binary tree and output the hierarchical traversal sequence of the binary tree. The method of establishing a binary tree by pre-order recursive traversal is: according to the idea of ​​pre-order recursive traversal, the abstract access to a binary tree node is embodied as whether to generate the node according to the received data, so as to realize the binary linked list storage structure of the binary tree. It is agreed that the binary tree node data is a single uppercase English character. When the received data is the character "#", it means that the node does not need to be created, otherwise create the node. Finally, output the hierarchical traversal sequence of the created binary tree. It is necessary to pay attention to the sequence and number relationship between "#" characters and non-"#" characters in the input data sequence, which will ultimately determine the shape of the created binary tree.

enter

The input is a string consisting of uppercase English characters and "#" characters that accepts keyboard input (used to create the corresponding binary tree).

output

Each use case uses a row to list the hierarchical traversal sequence of the binary tree corresponding to the use case.

sample input

A##
ABC####
ABC##
ABCD EFGH##
A##B##

Sample output

A
ABC
ABC
ABHCEDFG
A

General idea: Create a queue, first store the root node pointer of the tree, put its left and right sons in (first left and then right), and then put the root node pointer out of the opposite column, and keep looping until the queue is empty . (When a node is created, its left and right sons must be added to the team. If there are no left and right sons, it is ignored).

#include<iostream>
#include<stdlib.h>
#include<queue>//Use the head pointer of the queue
using namespace std;
typedef struct node
{
char data;
struct node *l,*r;
}Tree;
void init(Tree *&l)//Create a tree
{
char ch;
cin>>ch;
if(ch=='#') l=NULL;
else
{
l=(Tree *)malloc(sizeof(Tree));
l-> data=ch;
init(l->l);
init(l->r);
}
}
int main()
{
Tree *l;
init(l);
queue<node*>q;
q.push(l);
while(q.empty()==0)
{
Tree *T=q.front();//T to store the pointer to the head of the
queue q.pop();//Out of the column
cout<<T->data;
if(T->l!=NULL) q.push(T->l); 
if(T->r!=NULL) q.push(T->r);
}
return 0; 

Guess you like

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