PTA:前序序列创建二叉树

前序序列创建二叉树

题目

编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以二叉链表存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中"#"表示的是空格,代表一棵空树。然后再对二叉树进行中序遍历,输出遍历结果。

输入格式

多组测试数据,每组测试数据一行,该行只有一个字符串,长度不超过100。

输出格式

对于每组数据,

输出二叉树的中序遍历的序列,每个字符后面都有一个空格。

每组输出一行,对应输入的一行字符串。

输入样例(及其对应的二叉树)

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

输出样例

c b e g d f a

代码

cpp 复制代码
#include<iostream>
#include<string>
using namespace std;

typedef struct treenode
{
    char val;
    struct treenode* left;
    struct treenode* right;
}treenode;


treenode* createnode(char a)
{
    treenode* newnode = new treenode;
    if (newnode == nullptr)
        return nullptr;
    newnode->left = nullptr;
    newnode->right = nullptr;
    newnode->val = a;
    return newnode;
}

treenode* createtree(string a, int* index)
{
    treenode* head = nullptr;
    if ((*index) < a.size() && a[*index] != '#')
    {

        head = createnode(a[*index]);
        ++(*index);
        head->left = createtree(a, index);
        ++(*index);
        head->right = createtree(a, index);
    }
    return head;
}
void inderoder(treenode* head)
{
    if (nullptr == head)
    {
        return;
    }
    inderoder(head->left);
    cout << head->val << " ";
    inderoder(head->right);
}
int main()
{
    string s;
    while (cin >> s)
    {
        int index = 0;
        treenode* head = createtree(s, &index);
        inderoder(head);
        cout << endl;
    }
}
相关推荐
2501_9219608524 分钟前
双相自指图与弦论边界非对易性的结构同源
数据结构
王老师青少年编程27 分钟前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:均分纸牌
c++·算法·编程·贪心·csp·信奥赛·均分纸牌
EQUINOX128 分钟前
2026年码蹄杯 本科院校赛道&青少年挑战赛道提高组初赛(省赛)第一场,个人题解
算法
萝卜小白30 分钟前
算法实习Day04-MinerU2.5-pro
人工智能·算法·机器学习
Liangwei Lin37 分钟前
洛谷 P3133 [USACO16JAN] Radio Contact G
数据结构·算法
weixin_513449961 小时前
PCA、SVD 、 ICP 、kd-tree算法的简单整理总结
c++·人工智能·学习·算法·机器人
code_pgf1 小时前
Qwen2.5-VL 算法解析
人工智能·深度学习·算法·transformer
烟锁池塘柳01 小时前
一文讲透 C++ / Java 中方法重载(Overload)与方法重写(Override)在调用时机等方面的区别
java·c++·面向对象
Code-keys2 小时前
Android Codec2 Filter 算法模块开发指南
android·算法·音视频·视频编解码
无忧智库2 小时前
低空经济新基建:构建低空飞行大数据中心与行业应用算法工厂的全景式蓝图(WORD)
算法