일지
자료구조...71
niamdank
2021. 3. 25. 19:20
이진 탐색 트리 삭제, 기능 메서드 구현
BinarySearchTree.cpp
/// <summary>
/// BinarySearchTree의 모든 노드를 제거한다.
/// </summary>
void BinarySearchTree::Clear()
{
while (m_root != nullptr)
{
Delete(m_root->m_data);
}
}
/// <summary>
/// BinarySearchTree에 지정된 값이 존재하는지 검색한다.
/// </summary>
/// <param name="value">검색할 값</param>
bool BinarySearchTree::Search(int value)
{
if (m_root == nullptr)
{
return false;
}
Node* target{ m_root };
while (target != nullptr)
{
if (target->m_data == value)
{
break;
}
if (target->m_data > value)
{
target = target->m_left;
}
else
{
target = target->m_right;
}
}
return target != nullptr;
}
main.cpp
#include <iostream>
#include "BinarySearchTree/BinarySearchTree.h"
// 생성한 자료구조 테스트용 메인
int main()
{
BinarySearchTree bst;
bst.Insert(5);
bst.Insert(3);
bst.Insert(1);
bst.Insert(0);
bst.Insert(4);
bst.Insert(8);
bst.Insert(7);
bst.Insert(9);
bst.PrintInfo();
bst.Delete(5);
bst.PrintInfo();
std::cout << std::boolalpha << bst.Search(5) << '\n';
std::cout << std::boolalpha << bst.Search(9) << '\n';
bst.Clear();
bst.PrintInfo();
}
실행 결과
----------------------
└ 5
└ 3
└ 1
└ 0
└ 4
└ 8
└ 7
└ 9
----------------------
----------------------
└ 4
└ 3
└ 1
└ 0
└ 8
└ 7
└ 9
----------------------
false
true
----------------------
----------------------