二叉搜索树和AVL树的公共节点结构

时间:2014-10-25 17:24:29

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

我想为二叉搜索树(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;指向结构CommonNodep是指向结构AVLTree的指针。 我的问题是,为这个问题定义公共节点结构的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

这可能对您有帮助

#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