【问题标题】:BST Links and cases not workingBST 链接和案例不起作用
【发布时间】:2016-02-15 06:09:40
【问题描述】:

我有一个这样的嵌套结构

typedef struct Node_link {
    struct Node_base *parent, *left, *right;
}Node_link;


typedef struct Node_base {
    struct Node_link link[2];
}Node_base;

typedef struct Node{
    struct Node_base base;
    int size;
    int *address;
}Node;


Node_base *head[2] ={NULL, NULL}; 
//head[0] stores int size and head[1] it's corresponding address

节点有右、左和父链接,都是嵌套的,例如node->left->link.parent=node。我必须维护所有链接(父、左和右)并删除节点。 我已经尝试了很多案例,但仍然缺少一些。有人可以告诉我我需要使用哪些案例吗?或者向我介绍一些材料?我搜索了很多但没有成功。 我的插入函数如下:

Node_base *   insert(Node_base *location, Node_base *n) {
    if (head[0]==NULL)
    head[0]=n;
else
{
    if (location==NULL){
        location=n;
        return location;
    }
    else{

        if(((Node *)n)->size < ((Node *)location)->size){
            if(location->link[0].left==NULL)
            {
                location->link[0].left=n;
                location->link[0].left->link[0].parent=location;
            }
            else
                location->link[0].left=insert(location->link[0].left,n);
        return location;
    }
}

而且我对 head[1] 有相同的嵌套插入函数,它存储插入到 head[0] 中的节点的大小。

【问题讨论】:

  • 你的结构对我来说似乎全错了。您的插入函数不应该接受节点类型吗?为什么你甚至需要在 Node 和 Node_base 之间进行分离?为什么 Node_base 需要 2 个 Node_link 结构?其中哪一部分交给了你,你自己实现了什么?

标签: c binary-search-tree


【解决方案1】:

很难说这里发生了什么。你的代码看起来不像我见过的任何 BST 实现。为什么需要 Node_Link 结构? Node 结构中的指针应该定义链接是什么。为什么是父指针?在标准的 BST 实施中不应该需要这样。您只需要:

struct node {
    node *left;
    node *right;
    void *data;
    int size;
};

struct bst {
    node *root;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2017-06-14
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    相关资源
    最近更新 更多