My English is not very good, I’m sorry.I’m a beginner and want to do a problem with Ternary search tree. The problem occurs during the insertion of the node,VS throws an exception in insert_BiTreeNode: Read access violation. 0xcdcdcdcd {key=??? left=??? mid=??? …}
I don’t know how to fix it.
Below is my code
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int key;
struct BiTNode *left;
struct BiTNode *mid;
struct BiTNode *right;
}BiTNode, *BiTree;
int Max(int a, int b, int c) {
if (a >= b && a >= c)
return a;
else if (c >= a && c >= b)
return c;
else if (b >= a && b >= c)
return b;
}
BiTree create_BiTreeNode(int key) {
BiTNode* node = (BiTNode*)malloc(sizeof(BiTNode));
node->key = key;
node->left = NULL;
node->right = NULL;
return node;
}
BiTree insert_BiTreeNode(BiTNode* root, int key) {
if (root == NULL) {
root = create_BiTreeNode(key);
return root;
}
if (key < root->key - 500) {
root->left = insert_BiTreeNode(root->left, key);
}
else if (key > root->key + 500) {
root->right = insert_BiTreeNode(root->right, key);
}
else {
root->mid = insert_BiTreeNode(root->mid, key);
}
return root;
}
int TreeHeight(BiTNode* root)
{
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL && root->mid == NULL) {
return 1;
}
return Max(TreeHeight(root->left), TreeHeight(root->right), TreeHeight(root->mid)) + 1;
}
int main(){
BiTNode* root = NULL;
int N;
scanf_s("%d", &N);
int* arr = (int*)malloc(sizeof(int)* N);
for (int i = 0; i < N; i++) {
scanf_s("%d", &arr[i]);
root = insert_BiTreeNode(root, arr[i]);
}
int res = TreeHeight(root);
printf("%d", res);
free(arr);
return 0;
}
New contributor
user25600088 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.