KY207 二叉排序樹
題目描述
輸入一系列整數,建立二叉排序樹,並進行前序,中序,後序遍歷。
輸入描述:
輸入第一行包括一個整數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
題解:
#include <set>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
struct node{
int val;
node *left;
node *right;
node(int x) : val(x), left(NULL), right(NULL){}
};
node* root = NULL;
int insert_BST(int x){
node* temp = root;
if(root == NULL){
root = new node(x);
return -1;
}
//記錄插入節點是插在父節點的右邊還是左邊
//約定flag爲0的時候在父節點的左邊插入新節點,flag爲1的時候在父節點的右邊插入新節點
int flag = 0;
node* parent;
while(temp != NULL){
parent = temp;
//x比當前節點值大,去右邊找
if(x > temp->val){
flag = 1;
temp = temp->right;
}else{//題目保證數字互不相同
flag = 0;
temp = temp->left;
}
}
if(flag == 1){
parent->right= new node(x);
}else{
parent->left = new node(x);
}
return parent->val;
}
int main(){
int t, n;
scanf("%d", &t);
for(int i = 1; i <= t; i++){
scanf("%d", &n);
int x = insert_BST(n);
printf("%d\n", x);
}
return 0;
}