7-3. [C++] 이진 탐색 트리의 삽입 연산

2023. 7. 26. 01:17·Computer Science/Data Structure

이진 탐색 트리의 삽입 연산

앞 내용과 이어지므로 앞 내용을 보지 않았다면 아래 링크를 통해 보는 것을 추천한다.

https://seongmoahn.tistory.com/100

 

7-2. [C++] 이진 탐색 트리의 탐색 연산

이진 탐색 트리의 탐색 연산 앞 내용과 이어지므로 앞 내용을 보지 않았다면 아래 링크를 통해 보는 것을 추천한다. https://seongmoahn.tistory.com/99 7-1. [C++] 이진 탐색 트리란? 탐색이란? 탐색(search)은

seongmoahn.tistory.com

이진 탐색 트리에 새로운 노드를 삽입하기 위해서는 먼저 탐색을 수행해야 한다.

이진 탐색 트리에서는 같은 키 값을 갖는 노드가 없어야 하며, 탐색에 실패한 위치가 새로운 노드를 삽입하는 위치가 되기 때문이다.

탐색 과정에서 삽입하려는 노드의 키 값과 같은 키 값을 갖는 노드가 있다면 해당 노드는 삽입하지 않으면 된다.

탐색에 실패했다면 실패로 끝난 위치에 새로운 노드를 삽입하면 되는 것이다.

insert(root, node) // 이진 탐색 트리 삽입 알고리즘

if KEY(node) = KEY(root)
	then return ;
else if KEY(node) < KEY(root) then
	if LEFT(root) = NULL
    	then LEFT(root) <- node;
        else insert(LEFT(root), node);
else
	if RIGHT(root) = NULL
    	then RIGHT(root) <- node;
        else insert(RIGHT(root), node);

삽입 연산 구현

위 알고리즘을 바탕으로 이진 탐색 트리의 삽입 연산을 구현해보자.

// BiSearchTree.h
#include "BinaryTree.h"

class BiSearchTree : public BinaryTree {
public:
...    
    void insert(BinaryNode *newNode) {
        if (isEmpty()) root = newNode;
        else insert(root, newNode);
    }
    void insert(BinaryNode *rootNode, BinaryNode *newNode) {
        if (newNode->getData() == rootNode->getData()) return ;
        else if (newNode->getData() < rootNode->getData()) {
            if (rootNode->getLeft() == NULL) rootNode->setLeft(newNode);
            else insert(rootNode->getLeft(), newNode);
        }
        else {
            if (rootNode->getRight() == NULL) rootNode->setRight(newNode);
            else insert(rootNode->getRight(), newNode);
        }
    }
...
};
// BiSearchTree.cpp
#include "BiSearchTree.h"

int main() {
    BiSearchTree tree;

    BinaryNode *G = new BinaryNode(27, NULL, NULL);
    BinaryNode *F = new BinaryNode(31, G, NULL);
    BinaryNode *E = new BinaryNode(12, NULL, NULL);
    BinaryNode *D = new BinaryNode(3, NULL, NULL);
    BinaryNode *C = new BinaryNode(26, NULL, F);
    BinaryNode *B = new BinaryNode(7, D, E);
    BinaryNode *A = new BinaryNode(18, B, C);
    tree.setRoot(A);
    
    tree.search(9);

    BinaryNode *H = new BinaryNode(9, NULL, NULL);
    tree.insert(H);

    tree.search(9);

    return 0;
}

/*
실행 결과 :
key 값이 9인 노드 탐색 실패
key 값이 9인 노드 탐색 성공
*/

위 코드는 아래 이미지를 클릭해 깃허브에서도 확인할 수 있다.

깃허브 이미지 링크

저작자표시 (새창열림)

'Computer Science > Data Structure' 카테고리의 다른 글

7-5. 이진 탐색 트리의 성능 분석  (0) 2023.07.26
7-4. [C++] 이진 탐색 트리의 삭제 연산  (0) 2023.07.26
7-2. [C++] 이진 탐색 트리의 탐색 연산  (0) 2023.07.26
7-1. [C++] 이진 탐색 트리란?  (0) 2023.07.26
6-7. [C++] 스레드 이진 트리  (0) 2023.07.25
'Computer Science/Data Structure' 카테고리의 다른 글
  • 7-5. 이진 탐색 트리의 성능 분석
  • 7-4. [C++] 이진 탐색 트리의 삭제 연산
  • 7-2. [C++] 이진 탐색 트리의 탐색 연산
  • 7-1. [C++] 이진 탐색 트리란?
Study with Me!
Study with Me!
Study with Me!
  • Study with Me!
    Seongmo
    Study with Me!
  • 전체
    오늘
    어제
    • Computer (136)
      • Computer Science (61)
        • Data Structure (51)
        • Algorithm (6)
        • 선형대수 with C++ (4)
      • Arm Architecture (1)
        • Register (0)
        • Assembly Instruction (1)
      • Linux (32)
        • Linux Kernel (4)
        • 라이브러리 함수 구현하기 (0)
        • 쉘, 쉘 명령어 구현하기 (15)
        • Ubuntu (13)
      • Cloud Infrastructure (8)
        • Kubernetes (7)
        • OpenStack Magnum (1)
      • AWS (3)
      • Baekjoon (18)
      • Tools (6)
        • Git & Github (5)
        • Vim (1)
      • 개발 환경 (7)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    STL
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Study with Me!
7-3. [C++] 이진 탐색 트리의 삽입 연산
상단으로

티스토리툴바