给出 n 个数,建成一棵搜索二叉树
#include<bits/stdc++.h>
using namespace std;
struct node{
int value;
node *left;
node *right;
};
void insert(node *root, int x)
{
if(x > root -> value)
{
if(root -> right != NULL) insert(root -> right, x);
else
{
node *tmp = new node();
tmp -> left = NULL;
tmp -> right = NULL;
tmp -> value = x;
root -> right = tmp;
}
}
else
{
if(root -> left != NULL) insert(root -> left, x);
else
{
node *tmp = new node();
tmp -> left = NULL;
tmp -> right = NULL;
tmp -> value = x;
root -> left = tmp;
}
}
}
void ZB(node *root)
{
if(root != NULL)
{
if(root -> left != NULL) ZB(root -> left);
cout<<root -> value;
if(root -> right != NULL) ZB(root -> right);
}
}
int main()
{
int n;
node *tree = new node();
scanf("%d",&n);
int x;
scanf("%d",&x);
tree -> left = tree -> right = NULL;
tree -> value = x;
for(int i=2;i<=n;i++)
{
scanf("%d",&x);
insert(tree, x);
}
ZB(tree);
return 0;
}