| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 703 人关注过本帖
标题:[求助]在排序二叉树中插入一个结点X
取消只看楼主 加入收藏
shashaxia
Rank: 1
等 级:新手上路
帖 子:11
专家分:0
注 册:2005-12-11
收藏
 问题点数:0 回复次数:0 
[求助]在排序二叉树中插入一个结点X
[求助]在排序二叉树中插入一个结点X
能帮我看一下算法那里设计错了吗 ^_^
#include "stdio.h"
#include "conio.h"
struct node
{
int data;
struct node *lchild;
struct node *rchild;
struct node *parent;
}*root,*p,*tree,*f;
main()
{
void inorder(struct node *root);
void search(struct node *root,struct node *tree);
int find(struct node *root,int x,struct node *f);
int insert(int i,struct node *p,int x);
char c;
int i,j,x;
do
{
root=(struct node *)malloc(sizeof(struct node));
printf("\n\nplease enter root's node(-1 to end)");
if(scanf("%d",&root->data)&&root->data==-1)
printf("\n\nThe linary tree has no any nodes");
else
{
root->parent=NULL;
root->lchild=NULL;
root->rchild=NULL;
printf("\n\nPlease enter tree's node(-1 to end)\n");
do
{
tree=(struct node *)malloc(sizeof(struct node));
scanf("%d",&tree->data);
if(tree->data!=-1)
{
tree->parent=NULL;
tree->lchild=NULL;
tree->rchild=NULL;
search(root,tree);
if(p->data<tree->data)
p->rchild=tree;
else if(p->data>tree->data)
p->lchild=tree;
else
free(tree);
tree->parent=p;
}
}while(tree->data!=-1);
printf("\n\nCreating binary tree is:\n");
inorder(root);
}
printf("\n\nDo you want to create a new tree again? (Y,y(Yes) or N,n(No))");
}while((scanf("%c",&c)&&c=='Y')||(scanf("%c",&c)&&c=='y'));
printf("\n enter the x to insert:");
scanf("%d",&x);
printf("%d",x);
f=NULL;
i=find(root,x,f);
j=insert(i,root,x);
if(j==0)
printf("\nx is already in the tree");
else
{
printf("\nthe new tree is :");
inorder(root);
}
getch();
}
void inorder(struct node *root)
{
if(root!=NULL)
{
inorder(root->lchild);
printf("%d\t",root->data);
inorder(root->rchild);
}
}
void search(struct node *root,struct node *tree)
{
if((root->data<tree->data)&&(root->rchild!=NULL))
search(root->rchild,tree);
else if((root->data>tree->data)&&(root->lchild!=NULL))
search(root->lchild,tree);
else
p=root;
}
int find(struct node *root,int x,struct node *f)
{
if(root==NULL)
{
p=f;
return(0);
}
else if(root->data==x)
{
p=root;
return(1);
}
else if(root->data>x)
return(find(root->lchild,x,root));
else
return(find(root->rchild,x,root));
}
int insert(int i,struct node *p,int x)
{
struct node *s;
if(i==0)
{
s=(struct node *)malloc(sizeof(struct node));
s->data=x;
s->lchild=s->rchild=NULL;
if(p==NULL)
root=s;
else if(p->data>x)
p->lchild=s;
else
p->rchild=s;
return(1);
}
搜索更多相关主题的帖子: 结点 二叉树 
2005-12-22 13:12
快速回复:[求助]在排序二叉树中插入一个结点X
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015724 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved