PTA:前序序列创建二叉树

编程入门 行业动态 更新时间:2024-10-18 10:33:27

PTA:前序<a href=https://www.elefans.com/category/jswz/34/1769864.html style=序列创建二叉树"/>

PTA:前序序列创建二叉树

前序序列创建二叉树

  • 题目
    • 输入格式
    • 输出格式
    • 输入样例(及其对应的二叉树)
    • 输出样例
  • 代码

题目

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

输入格式

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

输出格式

对于每组数据,
输出二叉树的中序遍历的序列,每个字符后面都有一个空格。
每组输出一行,对应输入的一行字符串。

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

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

输出样例

c b e g d f a

代码

#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;}
}

更多推荐

PTA:前序序列创建二叉树

本文发布于:2023-11-16 15:00:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627329.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   二叉树   PTA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!