【发布时间】: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->nodePtr->left; 指向结构CommonNode,而p 是指向结构AVLTree 的指针。
我的问题是,为这个问题定义公共节点结构的正确方法是什么?
【问题讨论】:
-
在 64 位系统上,
struct CommonNode中会有 32 位的填充。您不妨将balanceFactor添加到该结构中,并为自己省去所有的焦虑。在 32 位系统上,这意味着公共节点在 BST 中使用的 32 位比最低要求多。你必须判断这对你来说是否是个问题——但使用单一结构会更简单。此外,struct AVLTree和struct bsTree都可以直接持有struct CommonNode,而不是指向struct CommonNode的指针——这是完全不必要的间接级别。 -
@JonathanLeffler 谢谢你的建议,有道理
标签: c struct binary-search-tree avl-tree