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;
    }
}
相关推荐
抓饼先生22 分钟前
C++ 20 视图view笔记
linux·开发语言·c++·笔记·c++20
大可门耳28 分钟前
qt调用cef的Demo,实现js与C++之间的交互细节
javascript·c++·经验分享·qt
半桔34 分钟前
【STL源码剖析】二叉世界的平衡:从BST 到 AVL-tree 和 RB-tree 的插入逻辑
java·数据结构·c++·算法·set·map
R_.L1 小时前
【项目】 :C++ - 仿mudou库one thread one loop式并发服务器实现(代码实现)
服务器·开发语言·c++
R_.L1 小时前
【项目】 :C++ - 仿mudou库one thread one loop式并发服务器实现(模块划分)
服务器·c++
塔中妖1 小时前
【华为OD】分割数组的最大差值
数据结构·算法·华为od
weixin_307779132 小时前
最小曲面问题的欧拉-拉格朗日方程 / 曲面极值问题的变分法推导
算法
RTC老炮2 小时前
webrtc弱网-AlrDetector类源码分析与算法原理
服务器·网络·算法·php·webrtc
孤廖2 小时前
【算法磨剑:用 C++ 思考的艺术・Dijkstra 实战】弱化版 vs 标准版模板,洛谷 P3371/P4779 双题精讲
java·开发语言·c++·程序人生·算法·贪心算法·启发式算法
躯坏神辉2 小时前
c++怎么读取文件里的内容和往文件里写入数据
c++