다음은 C언어로 작성된 Binary Search Tree의 예시야. #include <stdio.h> #include <stdlib.h> typedef…
- User
다음은 C언어로 작성된 Binary Search Tree의 예시야.
#include <stdio.h> #include <stdlib.h>
typedef struct { int key; } element;
typedef struct node *treePointer; struct node { element data; treePointer leftChild; treePointer rightChild; };
element* search(treePointer root, int k) { if (!root) return NULL; if (k == root->data.key) return &(root->data);
if (k < root->data.key) return search(root->leftChild, k); else return search(root->rightChild, k);}
treePointer modifiedSearch(treePointer root, int k) { if (!root || k == root->data.key) return NULL;
if (k < root->data.key && root->leftChild) return modifiedSearch(root->leftChild, k); else if (k > root-> data.key && root->rightChild) return modifiedSearch(root->rightChild, k); return root;}
void insert(treePointer *node, int k) { treePointer ptr; treePointer temp = modifiedSearch(*node, k);
if (temp || !(*node)) { ptr = malloc(sizeof(*ptr)); ptr->data.key = k; ptr->leftChild = ptr->rightChild = NULL; if (*node) { if (k < temp->data.key) temp->leftChild = ptr; else temp->rightChild = ptr; } else { *node = ptr; } }}
int main() { treePointer root = NULL;
insert(&root, 1); insert(&root, 3); insert(&root, 5); return 0;}
이진 탐색 트리에 노드를 삭제하는 함수 delete를 구현해줘. Key가 x인 함수를 작성해주면 돼. 노드가 존재할 경우 삭제한 노드의 Key를 반환하고 존재하지 않을 경우 NULL을 반환하도록 작성해줘.
- Assistant