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;
    }
}
相关推荐
我是苏苏3 小时前
C#高级:程序查询写法性能优化提升策略(附带Gzip算法示例)
开发语言·算法·c#
sali-tec4 小时前
C# 基于halcon的视觉工作流-章56-彩图转云图
人工智能·算法·计算机视觉·c#
学涯乐码堂主7 小时前
GESP C++ 四级第一章:再谈函数(上)
c++·青少年编程·gesp·四级·学漄乐码青少年编程培训
黑岚樱梦7 小时前
代码随想录打卡day23:435.无重叠区间
算法
微露清风7 小时前
系统性学习C++-第九讲-list类
c++·学习·list
大佬,救命!!!7 小时前
C++多线程同步与互斥
开发语言·c++·学习笔记·多线程·互斥锁·同步与互斥·死锁和避免策略
Kuo-Teng8 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
散峰而望8 小时前
C++入门(一)(算法竞赛)
c语言·开发语言·c++·编辑器·github
C_Liu_8 小时前
13.C++:继承
开发语言·c++