element* search(treePointer root, int k) {
/* return a pointer to the element whose key is k, if there is no such
element, return NULL */
if(!root) return NULL;
if(k == root->data.key) return &(root->data);
if(k < root->data.key) return search(root->leftChild, k);
return search(root->rightChild, k);
}
element* iterSearch(treePointer tree, int k) {
/* return a pointer to the element whose key is k, if there is no such
element, return NULL */
while(tree) {
if(k == tree->data.key) return &(tree->data);
if(k < tree->data.key)
tree = tree->leftChild;
else
tree = tree->rightChild;
}
return NULL;
}
O(h) = O(log n)
키가 이미 존재하면 삽입X
존재하지 않으면 search가 끝난 지점에 삽입
void insertNode(treePointer *node, int k) {
/* if the key k is already in the tree, do nothing; otherwise add a new
node with key k */
treePointer ptr, temp = modifiedSearch(*node, k); /* temp : 넣어야 할 위치의 부모 */
if(temp) {
/* k is not in the tree */
ptr = (treePointer)malloc(sizeof(*ptr));
ptr->data.key = k;
ptr->leftChild = ptr->rightChild = NULL;
if(*node) { /* not empty */
if(k < temp->data.key) temp->leftChild = ptr;
else temp->rightChild = ptr;
}
else *node = ptr; /* empty */
}
}
treePointer modifiedSearch(treePointer node, int k) {
treePointer parent = NULL;
while(node) {
// if we found a node with key k, we return NULL
if(k == node->data.key) return NULL;
parent = node;
if(k < node->data.key) node = node->leftChild;
else node = node->rightChild;
}
return parent;
}
빈 트리거나 키가 존재하면 널 반환