二叉树的生成与遍历

#include <stdio.h>
#include <stdlib.h>


struct node
{
int d;
struct node * lchild;
struct node * rchild;
};


struct node * CreateList(void); //生成二叉树 
struct node * InsertList(struct node * root,int x); //插入二叉树节点,小于根节点的作为左孩子,大于作为右孩子 
struct node * SearchList(struct node * root,int x); //查找节点 
void LeftList(struct node* root);   //左遍历二叉树 


void main()
{
int key; 
struct node * root,*s;
root=CreateList();
printf("%d\n",root->d);
LeftList(root);

printf("input insert  key value\n");
scanf("%d",&key);  //不要写成 scanf("%d\n",&key); 否则需要多输入一些字符 
root=InsertList(root,key); 

printf("input the key needed to search\n");
scanf("%d",&key);  不要写成 scanf("%d\n",&key); 否则需要多输入一些字符  
s=SearchList(root,key);
if(s==NULL)
printf("No %d\n",key);
else
printf("Yes %d\n",key);

LeftList(root);
return ;

}


struct node * SearchList(struct node * root,int x)
{


if(root==NULL||(root->d==x))     //停止递归调用的条件 
return root;
if(x<root->d)
return SearchList(root->lchild,x); //将左子树作为新的树来查找 ,递归思想 
else
    return SearchList(root->rchild,x);//将右子树作为新的树来查找 ,递归思想 
}


void LeftList(struct node* root)
{
if(root!=NULL)
{
printf("%d\n",root->d);  //递归遍历整个二叉树 
LeftList(root->lchild);
LeftList(root->rchild);
}
return ;
}


struct node * InsertList(struct node * root ,int x)
{   
struct node * p,*f;
    p=root;                  //使p指向root,这样可以找到二叉树的根,随后对p的操作也不会影响root 

while(p!=NULL)      //p从root开始遍历,找到适合的插入点后退出,规定左孩子小于根,右孩子大于根, 
{
if(x==p->d)
return root;
f=p;
if(x>p->d)
p=p->rchild;
else
p=p->lchild;
}

p=(struct node *)malloc(sizeof(struct node));
p->d=x;
p->lchild=NULL;
p->rchild=NULL;

if(root==NULL)
root=p;
else
{
if(x<f->d)
f->lchild=p;   //插入节点 

else
f->rchild=p;   //插入节点 
    }
    
    return root;



struct node * CreateList(void)
{   
struct node * root=NULL;
int x;
scanf("%d",&x);
while(x)
{
root=InsertList( root, x);  //生成二叉树的过程调用InsertList函数 
scanf("%d",&x);
}
return root;
}







































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值