【id:378】【5分】A. 二叉树构建与两种遍历

本文介绍了一段C++代码,用于根据给定的先序遍历结果创建二叉树的二叉链式存储结构,并输出对应的先序、中序和后序遍历结果。
摘要由CSDN通过智能技术生成

题目描述

给定一颗二叉树的逻辑结构如下图,(先序遍历的结果,空树用字符‘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;

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值