tree.c

/*二叉树实现*/
#include"tree.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>

static  SeekItem( const Item * pi, Tree * ptree);
static  Node * MakeNode(const Item * pi);
static  bool ToLeft(const Item *pi1, const Item * pi2);
static  bool ToRight(const Item *pi1, const Item * pi2);
bool AddITem(const Item * pi, Tree * ptree)
{
    Node * new_node;

    if (TreeIsFull(ptree))
    {
        fprintf(stderr, "Tree is full.\n");
        return false;
    }
    if (SeekItem(pi, ptree).child != NULL)
    {
        fprintf(stderr, "Attemppted to add duplicate item\n");
        return false;
    }
    new_node = MakeNode(pi);
    if (new_node == NULL)
    {
        fprintf(stderr, "Couldn't create node\n");
        return false;
    }
    /*成功创建了一个新节点*/
    ptree->size++;

    if (ptree->root == NULL)
        ptree->root = new_node;
    else
        AddNode(new_node, ptree->root);
    return true;
}
static Node * MakeNode(const Item * pi)
{
    Node * new_node;

    new_node = (Node *)malloc(sizeof(Node));
    if (new_node != NULL)
    {
        new_node->item = *pi;
        new_node->left = new_node->right = NULL;
        return new_node;
    }
    else
        return NULL;
}
static void AddNode(Node * new_node, Node * root)
{
    if (ToLeft(&new_node->item, &root->item))
    {
        if (root->left == NULL)
            root->left = new_node;
        else
            AddNode(new_node, root);
    }
    else if (ToRight(&new_node->item, &root->item))
    {
        if (root->right == NULL)
            root->right = new_node;
        else
            AddNode(new_node, root);
    }
    else
    {
        fprintf(stderr, "location error in AddNode()\n");
        exit(1);
    }
}
static  bool ToLeft(const Item *pi1, const Item * pi2)
{
    int comp1;

    if ((comp1 = strcmp(pi1->petname, pi2->petname)) < 0)
        return true;
    else if (comp1 = 0 && strcmp(pi1->petkind, pi2->petkind) < 0)
        return true;
    else
        return false;
}
static bool toRight(const Item * pi1, const Item * pi2)
{
    int comp1;

    if ((comp1 = strcmp(pi1->petname, pi2->petname)) > 0)
        return true;
    else if (comp1 = 0 && strcmp(pi1->petkind, pi2->petkind) > 0)
        return true;
    else
        return false;
}
/*其余部分在脑海里过了,今天就不写了*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值