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;
    }
}
相关推荐
咸鱼加辣几秒前
【python面试】Python 的 lambda
javascript·python·算法
Jerryhut5 分钟前
sklearn函数总结十二 —— 聚类分析算法K-Means
算法·kmeans·sklearn
Swift社区25 分钟前
LeetCode 453 - 最小操作次数使数组元素相等
算法·leetcode·职场和发展
八月ouc27 分钟前
Python实战小游戏(二): 文字冒险游戏
数据结构·python·文字冒险
渡我白衣28 分钟前
计算机组成原理(8):各种码的作用详解
c++·人工智能·深度学习·神经网络·其他·机器学习
hoiii18730 分钟前
LR算法辅助的MIMO系统Zero Forcing检测
算法
糖葫芦君32 分钟前
Lora模型微调
人工智能·算法
EXtreme3537 分钟前
【数据结构】二叉树进阶:层序遍历不仅是按层打印,更是形态判定的利器!
c语言·数据结构·二叉树·bfs·广度优先搜索·算法思维·面试必考
小李小李快乐不已41 分钟前
二叉树理论基础
数据结构·c++·算法·leetcode
仰泳的熊猫1 小时前
1149 Dangerous Goods Packaging
数据结构·c++·算法·pat考试