일지

자료구조...70

niamdank 2021. 3. 24. 19:52

이진 탐색 트리 삽입 메서드 구현

더블 포인터 구현을 싱글 포인터 구현으로 변경

 

BinarySearchTree.cpp

/// <summary>
/// 
/// </summary>
/// <param name="value">추가할 값</param>
void BinarySearchTree::Insert(int value)
{
	if (m_root == nullptr)
	{
		m_root = PopNode(value);
		return;
	}

	Node* target{ m_root };
	while (target != nullptr)
	{
		if (target->m_data == value)
		{
			break;
		}

		if (target->m_data > value)
		{
			if (target->m_left == nullptr)
			{
				target->m_left = PopNode(value);
				m_count++;
			}
			target = target->m_left;
		}
		else
		{
			if (target->m_right == nullptr)
			{
				target->m_right = PopNode(value);
				m_count++;
			}
			target = target->m_right;
		}
	}
}

 

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();
}

 

실행 결과

----------------------
└  5
  └  3
    └  1
      └  0
    └  4
  └  8
    └  7
    └  9
----------------------

----------------------
└  4
  └  3
    └  1
      └  0
  └  8
    └  7
    └  9
----------------------