二叉排序树 九度教程第35题 二叉排序树的构建与遍历

题目链接

来源:牛客网
输入一系列整数,建立二叉排序树,并进行前序,中序,后序遍历。
输入描述:
输入第一行包括一个整数n(1<=n<=100)。
接下来的一行包括n个整数。
输出描述:
可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。
每种遍历结果输出一行。每行最后一个数据之后有一个空格。
输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。
示例1
输入
5
1 6 5 9 8
输出
1 6 5 9 8
1 5 6 8 9
5 8 9 6 1

解题思路:
二叉排序树的构建与三种遍历方式。

AC代码:

#include<iostream>
#include<stdio.h>
using namespace std;
struct node {
	node *left;
	node *right;
	int num;
}tree[105];//静态数组
int cnt;//静态数组中被使用元素的个数
node *creat() {//申请新结点
	tree[cnt].left = tree[cnt].right = NULL;
	return &tree[cnt++];
}
node *build(int x, node *t) {
	if (t == NULL) {//若当前树为空
		t = creat();//建立新结点
		t->num = x;
	}
	else if (x < t->num) {//进入左子树
		t->left = build(x, t->left);
	}
	else if (x > t->num) {//进入右子树 若根结点数值与x相等,按照题目要求直接忽略
		t->right = build(x, t->right);
	}
	return t;//返回根结点指针
}
void pre_order(node *root) {//前序遍历
	if (root == NULL) return;
	printf("%d ", root->num);
	pre_order(root->left);
	pre_order(root->right);
}
void in_order(node *root) {//中序遍历
	if (root == NULL) return;
	in_order(root->left);
	printf("%d ", root->num);
	in_order(root->right);
}
void post_order(node *root) {//后序遍历
	if (root == NULL) return;
	post_order(root->left);
	post_order(root->right);
	printf("%d ", root->num);
}
int main() {
	int n, x;
	while (scanf("%d", &n)!=EOF) {
		cnt = 0;
		node *t = NULL;
		for (int i = 1; i <= n; i++) {
			scanf("%d", &x);
			t = build(x, t);
		}
		pre_order(t);
		printf("\n");
		in_order(t);
		printf("\n");
		post_order(t);
		printf("\n");
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值