您的位置:首页 > 运维架构

OpenJudge4079:二叉搜索树

2015-10-30 17:29 507 查看
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
using namespace std;
typedef struct BiNode{
struct BiNode *left;
struct BiNode * right;
int num;
}BiNode,*BiTree;

BiTree tt;
int b[500];
//建树
void createTree(BiTree* root,int key)
{
//cout<<key;
BiTree t;
t = (BiTree)malloc(sizeof(BiNode));
t->left = NULL;
t->right = NULL;
t->num = key;

if(*root == NULL)
{
*root = t;
return;
}
if((*root)->left==NULL&&(*root)->num>key)
{
(*root)->left = t;
return;
}
if((*root)->right==NULL&&(*root)->num<key)
{
(*root)->right = t;
return;
}
if((*root)->num>key)
{
createTree(&(*root)->left,key);
return;
}
else if((*root)->num<key)
{
createTree(&(*root)->right,key);
return;
}
else
return;

}
//前序遍历
void display(BiTree t)
{
if(t!=NULL){
cout<<t->num<<" ";
display(t->left);
display(t->right);
}
}

int main()
{
int i = 0;
tt=NULL;
int a;

while(cin>>a)
{

b[i] = a;
createTree(&tt,b[i]);
i++;
//if(i==20) break;
}
//cout<<i;
display(tt);
//system("pause");
return 0;
}


4079:二叉搜索树

查看
提交
统计
提示
提问

总时间限制: 1000ms 内存限制: 1024kB
描述

   二叉搜索树在动态查表中有特别的用处,一个无序序列可以通过构造一棵二叉搜索树变成一个有序序列,构造树的过程即为对无序序列进行排序的过程。每次插入的新的结点都是二叉搜索树上新的叶子结点,在进行插入操作时,不必移动其它结点,只需改动某个结点的指针,由空变为非空即可。

   这里,我们想探究二叉树的建立和序列输出。

输入只有一行,包含若干个数字,中间用空格隔开。(数字可能会有重复)
输出输出一行,对输入数字建立二叉搜索树后进行前序周游的结果。
样例输入
41 467 334 500 169 724 478 358 962 464 705 145 281 827 961 491 995 942 827 436


样例输出
41 467 334 169 145 281 358 464 436 500 478 491 724 705 962 827 961 942 995
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: