我需要进行一次BST。但是,每个节点本质上都是可以添加到其中的二叉搜索树的根。示例是:
您在BST中存储了几家鞋店,但每家鞋店都携带不同的鞋
商店建成后,我不知道如何使用商店根(节点)并在每个商店下新建一棵树,其中将保留鞋子名称以及连接其他鞋子的左右指针。我需要做另一个插入函数吗?我知道我将必须释放内存,但是现在,我正在尝试找出其他节点的插入。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct mainNode {
char* name;// Shop Name
struct mainNode* left;
struct mainNode* right;
struct regNode* root; // Pointer To Sub Node
} MainTreeNode;
typedef struct regNode{
char * name;// Shoe Name
struct regNode *left;
struct regNode *right;
} regNode;
MainTreeNode* insert(MainTreeNode* root, char* name);
void inOrder(MainTreeNode* root);
int main() {
// Create tree
MainTreeNode* MainTreeRoot = NULL;
MainTreeRoot = insert(MainTreeRoot ,"nike");
MainTreeRoot = insert(MainTreeRoot, "adidas");
MainTreeRoot = insert(MainTreeRoot, "underArmour");
MainTreeRoot = insert(MainTreeRoot, "rebbok");
inOrder(MainTreeRoot);
printf("\n");
return 0;
}
// Inserts a new node into the tree rooted at root with data set to value.
// and returns a pointer to the root of the resulting tree.
MainTreeNode* insert(MainTreeNode* root,char* name) {
// Inserting into an empty tree.
if (root == NULL) {
MainTreeNode* temp = malloc(sizeof(MainTreeNode));
temp->name = name;
temp->left = NULL;
temp->right = NULL;
temp->root = NULL;
return temp;
}
// Go left
if (strcmp(name,root->name) < 0)
root->left = insert(root->left,name);
// Go right
else
root->right = insert(root->right, name);
// Must return the root of this tree
return root;
}
void inOrder(MainTreeNode* root){
if (root != NULL) {
inOrder(root->left);
printf("%s \n", root->name);
inOrder(root->right);
}
}