题解 | #二叉排序树#
二叉排序树
https://www.nowcoder.com/practice/30a0153649304645935c949df7599602
#include<iostream>
using namespace std;
struct treenode
{
int data;
treenode* lc;
treenode* rc;
treenode(int x):data(x),lc(NULL),rc(NULL){}
};
treenode* insert(treenode* root,int x,int father)
{
if(root==NULL)
{
printf("%d\n",father);
root=new treenode(x);
}
else if(x<root->data)
root->lc=insert(root->lc,x,root->data);
else
root->rc=insert(root->rc,x,root->data);
return root;
}
void preorder(treenode* root)
{
if(root==NULL)
return;
printf("%d ",root->data);
preorder(root->lc);
preorder(root->rc);
}
int main ()
{
treenode* root=NULL;//这个很重要
int a[100];
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
int x;
cin>>x;
root=insert(root,x,-1);
}
}
}
