강의

멘토링

로드맵

Inflearn Community Q&A

thd2tn1756's profile image
thd2tn1756

asked

Hong Jung-mo's C Programming: Learning by Doing (Appendix)

17.17 Implementing a Binary Search Tree ​

19:20 부분에서 질문있습니다.

Resolved

Written on

·

277

0

교수님께서 Seekitem()를 이용해서 pair를 return하는 방법에는 while문을 사용하는 방법 말고도 재귀호출을 사용하는 방법도 있다고 하셨습니다.

저는 재귀호출로 짜봤는데 아무래도 너무 지저분한 거 같습니다. 교수님이나 다른 분이 재귀호출을 사용하셨다면 어떤 식으로 코드를 짰을 지가 궁금합니다.

제가 짠 코드는 아래와 같습니다.

static Node* SeekParentNode(const Item* pi, Node* pnode)

{

if (pnode->left != NULL)

if (compare(pnode->left->item, *pi) == 0)

return pnode;

 

if (pnode->right != NULL)

if (compare(pnode->right->item, *pi) == 0)

return pnode;

 

if (compare(pnode->item, *pi) > 0)

{

if (pnode->left == NULL && pnode->right == NULL)

return NULL;

SeekParentNode(pi, pnode->left);

}

else if (compare(pnode->item, *pi) < 0)

{

if (pnode->left == NULL && pnode->right == NULL)

return NULL;

SeekParentNode(pi, pnode->right);

}

}

 

static Node* SeekChildNode(const Item* pi, Node* pnode)

{

if (compare(pnode->item, *pi) == 0)

return pnode;

 

if (compare(pnode->item, *pi) > 0)

{

if (pnode->left == NULL)

return NULL;

SeekChildNode(pi, pnode->left);

}

else

{

if (pnode->right == NULL)

return NULL;

SeekChildNode(pi, pnode->right);

}

}

 

static Pair SeekItem(const Item* pi, const Tree* ptree)

{

Pair found_pair;

found_pair.parent = SeekParentNode(pi, ptree->root);

found_pair.child = SeekChildNode(pi, ptree->root);

 

return found_pair;

}

c

Quiz

51% of people got it wrong. Give it a try!

When comparing arrays and linked lists, which data structure is more efficient for data insertion or deletion?

Array

Linked list

Stack

Q

Answer 1

1

작성해주신 코드도 정말 좋은 듯 합니다 :)

thd2tn1756's profile image
thd2tn1756

asked

Ask a question