問題 A: 二叉排序樹
時間限制: 1 Sec 內存限制: 32 MB
題目描述
輸入一系列整數,建立二叉排序數,並進行前序,中序,後序遍歷。
輸入
輸入第一行包括一個整數n(1<=n<=100)。接下來的一行包括n個整數。
輸出
可能有多組測試數據,對於每組數據,將題目所給數據建立一個二叉排序樹,並對二叉排序樹進行前序、中序和後序遍歷。每種遍歷結果輸出一行。每行最後一個數據之後有一個空格。
樣例輸入
1
2
2
8 15
4
21 10 5 39
樣例輸出
2
2
2
8 15
8 15
15 8
21 10 5 39
5 10 21 39
5 10 39 21
題意很簡單,按照給定序列建一顆二叉查找樹,要求輸出先序、中序和後序的序列。
坑點是:不能有重複的鍵值,這個我也試了好幾次才發現(坑啊),因爲有的書上說可以有重複的鍵值,有的書說沒有,但是題目也沒有說明(QWQ)
代碼:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node {
int data;
node* lc, * rc;
};
void insert(node*& root, int data) { //建樹
if (!root) {
root = new node;
root->data = data, root->lc = root->rc = NULL;
return;
}
if (data == root->data) return; //關鍵步驟(少了這一步只能得50分了~)
if (data < root->data) insert(root->lc, data);
else insert(root->rc, data);
}
void preorder(node* root) { //先序
if (!root) return;
printf("%d ", root->data);
preorder(root->lc);
preorder(root->rc);
}
void inorder(node* root) { //中序
if (!root) return;
inorder(root->lc);
printf("%d ", root->data);
inorder(root->rc);
}
void postorder(node* root) { //後序
if (!root) return;
postorder(root->lc);
postorder(root->rc);
printf("%d ", root->data);
}
int main() {
int n;
while (scanf("%d", &n) == 1) {
node* root = NULL;
for(int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
insert(root, x);
}
preorder(root);
printf("\n");
inorder(root);
printf("\n");
postorder(root);
printf("\n");
}
return 0;
}