题目1467:二叉排序树
算法分析
考察二叉排序数的基本操作,插入过程相对简单,value大于当前节点跳到右子树,value小于当前节点跳到左子树
插入过程和查找过程十分类似,不过在查找中需要判断当前节点是否等于value.
biNode* search(int value){
biNode *y = NULL;
biNode *x = root;
while(x!=NULL){
if(value > x->value){
y = x;
x = x->Left;
}
else{
y = x;
x = x->Right;
}
}
return x;
}
二叉排序数的其它操作参见 二叉排序数的总结
源程序
//============================================================================
// Name : judo1467.cpp
// Author : wdy
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
struct biNode{
int value;
biNode *parent;
biNode *Left;
biNode *Right;
public:
biNode(int value_):value(value_),parent(NULL),Left(NULL),Right(NULL){};
};
biNode *root = NULL;
void insert(int value){
biNode *temnode = new biNode(value);
if(root==NULL){
root = temnode;
std::cout<<-1<<std::endl;
return;
}
biNode *y = NULL;
biNode *x = root;
while(x!=NULL){
if(value > x->value){
y = x;
x = x->Left;
}
else{
y = x;
x = x->Right;
}
}
if(value > y->value){
y->Left = temnode;
}else{
y->Right = temnode;
}
std::cout<< y->value <<std::endl;
}
void init(int n){
root = NULL;
int value;
for(int i = 0;i<n;i++){
std::cin>>value;
insert(value);
}
}
void judo(){
int n = 0;
while(std::cin>>n){
init(n);
}
}
int main() {
//cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
judo();
return 0;
}
/**************************************************************
Problem: 1467
User: KES
Language: C++
Result: Accepted
Time:20 ms
Memory:1520 kb
****************************************************************/