题解 | #二叉排序树#

二叉排序树

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);
	}
	}

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务