牛客网-------KY207二叉排序树

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章