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;
    }
}
相关推荐
励志的小陈2 分钟前
数据结构---顺序表
数据结构
NAGNIP10 分钟前
面试官:正则化都有哪些经典的方法?
算法·面试
汉克老师24 分钟前
GESP2026年3月认证C++五级( 第三部分编程题(2)找数)
c++·排序·双指针·二分算法·gesp5级·gesp五级
长安第一美人26 分钟前
AI辅助下的嵌入式UI系统设计与实践(二)[代码阅读理解]
c++·嵌入式硬件·ui·显示屏·工业应用
Theodore_102232 分钟前
深度学习(12)正则化线性回归中的偏差与方差调试
人工智能·深度学习·算法·机器学习·线性回归
比昨天多敲两行41 分钟前
C++ 多态
开发语言·c++
是娇娇公主~1 小时前
C++ 多态机制与虚函数实现原理
c语言·c++
m0_569881471 小时前
跨语言调用C++接口
开发语言·c++·算法
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #295:数据流的中位数(双堆法、有序列表、平衡树等多种实现方案详解)
算法·leetcode·优先队列··数据流·中位数·java 面试题
x_xbx1 小时前
LeetCode:215. 数组中的第K个最大元素
数据结构·算法·leetcode