简体   繁体   中英

Having trouble understanding why we use and how to use two structs for a binary search tree

I'm working on a program that involves using a Binary search tree and I am trying to initialize the BST. But I'm having a hard time understanding why we use two structures, and why I am getting "request for member left in something not a structure or union"

#include <stdio.h>
#include <stdlib.h>
#define ADD_LENGTH 30



typedef struct treeType{
    int listingId, price, propertySize;
    int numOfBeds, yearBult;
    char agent[20];
    char address[ADD_LENGTH];
    struct treeType *left;
    struct treeType *right;

}bNode;

typedef struct treeFrame{
    bNode *node;

}bTree;
void init(bTree **tree);


int main(void)
{
    bTree *tree;
    init(&tree);

    return 0;
}

void init(bTree **tree){
    tree = NULL;
    tree->left = NULL;
    tree->node->right = NULL;


}

But I'm having a hard time understanding why we use two structures

You are dealing with two abstractions -- tree and nodes of a tree. It makes perfect sense to use two struct s, one for each abstraction.

Your posted struct for the tree, bTree , has only one member, the root node. You can potentially add other members to it -- the number of nodes in the tree, the maximum of depth of the leaf nodes in tree, etc. Granted that these can be computed but it might be useful to have them as member variables and update them when you modify the tree to make them available without the paying the cost of traversing the tree.

The main thing to remember is that a tree and the nodes of a tree are two different abstractions. They should be defined using two different struct s. Each can be extended/updated independently depending on the needs of the application.

why I am getting "request for member left in something not a structure or union"

Code in the function init is wrong for several reasons.

  1. You have not allocated any memory for the "tree".
  2. You are using the variable tree in correctly. In the function, tree of type bTree** . It is a pointer to a pointer to a bTree .
  3. bTree does not have a member called left . Hence your attempt to use tree->left = NULL; is not correct.

What you need is something like:

void init(bTree **tree) 
{
   // Allocate memory for the tree.
   *tree = malloc(sizeof(bTree));

   // Make the root node NULL to indicate it is an empty tree.
   (*tree)->node = NULL;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM