二叉树的插入建立

#include <stdlib.h>
#include <stdio.h>
typedef struct btnode
{
    int data;
    struct btnode *lchild,*rchild;
}btnode;
int b[100];
//在二叉树中插入元素
btnode *insertnode(btnode *root,int node)
{
    btnode *newnode;
    btnode *currentnode;
    btnode *parentnode;
    newnode=(btnode*)malloc(sizeof(btnode));
    newnode->lchild=NULL;
    newnode->rchild=NULL;
    newnode->data=node;
    if (root==NULL)
    return newnode;
    else
    {
        currentnode=root;
        while(currentnode!=NULL)
        {
            parentnode=currentnode;
            if (currentnode->data>node)
            currentnode=currentnode->lchild;
            else
            currentnode=currentnode->rchild;
        }
        if (parentnode->data>node)
        parentnode->lchild=newnode;
        else
        parentnode->rchild=newnode;
    }
    return root;
}
//建立二叉树
btnode* createtree(int *s,int len)
{
    btnode* root=NULL;
    for (int i=0;i<len;++i)
    root=insertnode(root,s[i]);
    return root;
}
//先序遍历输出二叉树
void preorder(btnode *root)
{
    if (root==NULL)
    return;
    else
    {
        printf ("%d",root->data);
        preorder(root->lchild);
        preorder(root->rchild);
    }
}
int main()
{
  int s[20];
    btnode* root;
    root=NULL;
    int len=0;
    int n;
    scanf("%d",&n);
    while(n!=0)
    {
        s[len]=n;
        len++;
        scanf("%d",&n);
    }
    root=createtree(s,len);
    printf ("the tree is created!\n");
    preorder(root);
    return 0;
}

 

转载于:https://www.cnblogs.com/1994two/p/3369122.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值