A - 数据结构实验之二叉树二:遍历二叉树 | SDUT OnlineJudgehttps://acm.sdut.edu.cn/onlinejudge3/contests/3982/problems/A本文借用SDUTOJ来测试
树的建立
输入的一个样例为
abc,,de,g,,f,,,
该样例以 ‘,’ 为空节点
//树的建立
node* buildtree()
{
node* root;
if (s[tot] == ',')
{
root = NULL;//叶节点为空
tot++;
}
else
{
root = new node;
root->data = s[tot++];//当前根节点赋值
root->l = buildtree();//递归实现左侧建树
root->r = buildtree();//左侧建树时右侧进入栈区遇到递归边界时出栈以实现从左向右从上往下建树
}
return root;
}
三种遍历方式
//三种遍历方式代码实现区别在于输出根节点的位置
//前序遍历(根左右)
void preorder(node* root)
{
if (root)
{
cout << root->data;
preorder(root->l);//输出根节点后输出左侧
preorder(root->r);
}
}
//中序遍历(左根右)
void midorder(node* root)
{
if (root)
{
midorder(root->l);
cout << root->data;//先输出左侧
midorder(root->r);
}
}
//后序遍历(左右根)
void postorder(node* root)
{
if (root)
{
postorder(root->l);
postorder(root->r);
cout << root->data;//输出完左侧右侧后输出根节点
}
}
用代码解决一下SDUTOJ的问题
A - 数据结构实验之二叉树二:遍历二叉树
Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。
Sample
Input
abc,,de,g,,f,,,
Output
cbegdfa
cgefdba
以下是ac代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include<bits/stdc++.h>
using namespace std;
const int Maxn=1e3+10;
char s[Maxn];
int tot=0;
typedef struct node
{
char data;
node* l, * r;
};
node* buildtree()//建树
{
node* root;
if (s[tot] == ',')
{
tot++;
root=NULL;
return root;
}
else
{
root = new node;
root->data = s[tot++];
root->l = buildtree();
root->r = buildtree();
}
return root;
}
void midorder(node *root)//中序遍历二叉树
{
if (root)
{
midorder(root->l);
cout << root->data;
midorder(root->r);
}
}
void posorder(node* root)//后序遍历二叉树
{
if (root)
{
posorder(root->l);
posorder(root->r);
cout << root->data;
}
}
int main()
{
node* root;
while (cin >> s)
{
tot = 0;//别忘了累加器归0
root = buildtree();
midorder(root);
cout << endl;
posorder(root);
cout << endl;
}
return 0;
}