题目描述
给定一颗二叉树的逻辑结构如下图,(先序遍历的结果,空树用字符‘0’表示,例如AB0C00D00),建立该二叉树的二叉链式存储结构,并输出该二叉树的先序遍历结果
输入
第一行输入一个整数t,表示有t个二叉树
第二行起输入每个二叉树的包含空树的先序遍历结果,空树用字符‘0’表示,连续输入t行
输出
输出每个二叉树的中后序两种遍历,两行结果
AC代码
#include <iostream>
#include <queue>
//#include "math.h"
#include "algorithm"
#include "stack"
#include "iomanip"
using namespace std;
int mmax=1000;
class node{
public:
char data;
node *left= nullptr;
node *right= nullptr;
};
node* Create(string str,int& index){
if(str[index]=='0'){
return nullptr;
}
node* tmp=new node;
tmp->data=str[index];
tmp->left= Create(str,++index);
tmp->right= Create(str,++index);
return tmp;
}
void Preorder(node* root){
if(!root)
return;
cout<<root->data;
Preorder(root->left);
Preorder(root->right);
}
void Midorder(node* root){
if(!root)
return;
Midorder(root->left);
cout<<root->data;
Midorder(root->right);
}
void Postorder(node* root){
if(!root)
return;
Postorder(root->left);
Postorder(root->right);
cout<<root->data;
}
int main() {
int t;
cin>>t;
while(t--){
string str;
cin>>str;
int index=0;
node* root = Create(str,index);
Midorder(root);
cout<<endl;
Postorder(root);
cout<<endl;
}
return 0;
}