【问题标题】:Common node structure for binary search tree and AVL tree二叉搜索树和AVL树的通用节点结构
【发布时间】:2014-12-21 07:25:29
【问题描述】:

我想为二叉搜索树 (BST) 和 AVL 树定义一个公共节点结构。为此,我在 CommonNode.h 文件中定义了以下结构。

struct CommonNode{
int data;
struct CommonNode *left, *right;
};
typedef struct CommonNode node;

在另一个文件 BST.h 中,我为 BST 节点定义了一个结构

struct bsTree{
node *nodePtr;
};
typedef struct bsTree bst;

在另一个文件 AVL.h 中,我为 AVL 节点定义了一个结构

struct AVLTree{
node *nodePtr;
int balanceFactor;
};
typedef struct AVLTree avl;

考虑以下代码(在树中搜索value 的代码)

avl *p;
p = root; // assume that pointer to root is given
while(p!=NULL){
    if(value < p->nodePtr->data)  // value
        p = p->nodePtr->left;
    else
        p = p->nodePtr->right;
}

此方法不正确,因为p-&gt;nodePtr-&gt;left; 指向结构CommonNode,而p 是指向结构AVLTree 的指针。 我的问题是,为这个问题定义公共节点结构的正确方法是什么?

【问题讨论】:

  • 在 64 位系统上,struct CommonNode 中会有 32 位的填充。您不妨将balanceFactor 添加到该结构中,并为自己省去所有的焦虑。在 32 位系统上,这意味着公共节点在 BST 中使用的 32 位比最低要求多。你必须判断这对你来说是否是个问题——但使用单一结构会更简单。此外,struct AVLTreestruct bsTree 都可以直接持有 struct CommonNode,而不是指向 struct CommonNode 的指针——这是完全不必要的间接级别。
  • @JonathanLeffler 谢谢你的建议,有道理

标签: c struct binary-search-tree avl-tree


【解决方案1】:

这可能对你有帮助

#include<stdio.h>
#include<malloc.h>

struct CommonNode{
int data;
struct CommonNode *left, *right;
};

typedef struct CommonNode node;

struct bsTree{
node *nodePtr;
};

typedef struct bsTree bst;

struct AVLTree{
node *nodePtr;
int balanceFactor;
};

typedef struct AVLTree avl;


int main()
{
avl *p;
p = (struct AVLTree*)malloc(sizeof(struct AVLTree));
p->nodePtr = (node*)malloc(sizeof(node));
p->nodePtr->data = 20;
printf("The data value is %d\n",p->nodePtr->data);
return 0;
}


OUTPUT:
The data value is 20

【讨论】:

  • 问题不在于访问数据,而在于指针类型。 p-&gt;nodePtr-&gt;left 指向 node,但我希望它指向 struct AVLTree
  • @Hegde 你所做的是正确的。你已经把一个通用的东西放在一个结构中,然后你将它用于 BST 和 AVL。根据您的说法,它类似于嵌套结构。 p->nodePtr->left 仅指向 AVL。就像在 AVL 中你有 CommonNode 结构。
猜你喜欢
  • 1970-01-01
  • 2016-11-06
  • 2016-01-07
  • 2013-01-18
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
相关资源
最近更新 更多