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;
}