码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构:二叉树

时间:2019-10-30 14:03:17      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:return   amp   mod   oid   gcd   inline   pre   roo   pos   

现给出扩展二叉树(‘ . ’表示子树为空)的前序序列,要求输出其前中后序序列。

input: ABD..EF..G..C..

//#include<bits/stdc++.h>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<set>
#include<cmath>
#include<map>
#include<queue>
using namespace std;
#define ll long long
#define ull unsigned long long
inline ll gcd(ll a, ll b) { return a == 0 ? b : gcd(b % a, a); }
inline ll lcm(ll a, ll b) { return (a * b) / gcd(a, b); }
inline ll rd() {
	ll x = 0, f = 1; char ch = getchar();
	while (ch<‘0‘ || ch>‘9‘) { if (ch == ‘-‘)f = -1; ch = getchar(); }
	while (ch >= ‘0‘ && ch <= ‘9‘) { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); }
	return x * f;
}
const int maxn = 1e3 + 10;
const int mod = 1e9 + 7;
typedef struct treepoint * T;
struct treepoint {
	char date;
	T lson, rson;
};
char s[110];
int pos ,len;
T build() {//建立二叉树
	T bt = (T)malloc(sizeof(treepoint));
	pos++;
	if (s[pos] == ‘.‘)bt = NULL;
	else {
		bt->date = s[pos];
		bt->lson = build();
		bt->rson = build();
	}
	return bt;
}
void pre_order_travel(T bt) {//前序遍历
	printf("%c", bt->date);
	if (bt->lson != NULL)
		pre_order_travel(bt->lson);
	if (bt->rson != NULL)
		pre_order_travel(bt->rson);
	//free(bt);
}
void mid_order_travel(T bt){//中序遍历
	if (bt->lson != NULL)
		mid_order_travel(bt->lson);
	printf("%c", bt->date);
	if (bt->rson != NULL)
		mid_order_travel(bt->rson);
	//free(bt);
}
void post_order_travel(T bt) {//后序遍历
	if (bt->lson != NULL)
		post_order_travel(bt->lson);
	if (bt->rson != NULL)
		post_order_travel(bt->rson);
	printf("%c", bt->date);
	//free(bt);
}
int main() {
	while (~scanf("%s", s + 1)) {
		T root = (T)malloc(sizeof(treepoint));
		len = strlen(s + 1);
		pos = 0;
		root=build();
		pre_order_travel(root);
		puts("");
		mid_order_travel(root);
		puts("");
		post_order_travel(root);
		puts("");
	}
}

  

数据结构:二叉树

标签:return   amp   mod   oid   gcd   inline   pre   roo   pos   

原文地址:https://www.cnblogs.com/fengfeng007/p/11764150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!