Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Introduction to Binary Trees and Binary Search Trees in Computer Science, Lecture notes of Algorithms and Programming

An overview of binary trees and binary search trees, including their structure, types, and operations such as traversal, search, insertion, and deletion. It also discusses the importance of balancing binary search trees for optimal performance.

Typology: Lecture notes

2017/2018

Uploaded on 10/23/2018

keehwan
keehwan 🇨🇦

20 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
- 127 -
제10장 이진 검색 트리
장에서는 트리 형태의 자료구조에 대해 살펴본다. 특히 트리 형태의 자료구조 이진
검색 트리(binary search tree) 대해 집중적으로 살펴본다.
10.1. 교육목표
장의 교육목표는 다음과 같다.
교육목표
트리 개요
이진 트리 개요
순회 방법
이진 검색 트리 ADT
검색
삽입
삭제
순회
이진 트리 균형 맞추기
10.2. 트리
트리 구조
선형 연결 리스트는 성능 측면에서는 배열을 이용한 리스트 구현에
비해 우수하지 못하지만 공간 활용 측면에서는 우수하다.
형연결리의또다른단은임의접을할수없
정렬된 리스트에서도 이진 검색을할수없는것.
선형 연결 리스트에서 하나의 노드는 오직 하나의 다른 노드만 가리킬
수있.
트리
트리(tree)
루트
루트(root)라고 하는 유일한
유일한 시작
시작 노드
노드를가,
노드는
노드는 여러
여러 개의
개의 자식
자식 노드를
노드를 가질
가질
있는
있는 구조
구조로서,
루트에서
루트에서
노드까지의
노드까지의 경로가
경로가 유일한
유일한 구조
구조를말.
트리는 재귀
재귀 구조
구조(recursive structure)이다.
노드를 기준으로 노드가 루트가 되는 부분트리
부분트리(subtree)
들수있.
7장에서 살펴본 연결구조 방식의 리스트는 5장에서 살펴본 배열을 이용한 리스트에 비해
공간 활용 측면에서는 우수하지만 성능 측면에서는 오히려 배열을 이용한 리스트가 우수
하다. 특히 정렬 리스트의 경우에는 배열은 임의 접근이 가능하므로 이진 검색을
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Introduction to Binary Trees and Binary Search Trees in Computer Science and more Lecture notes Algorithms and Programming in PDF only on Docsity!

검색 트리(binary search tree)에 대해 집중적으로 살펴본다.

이진 검색 트리 ADT

트리트리(tree)는

루트루트(root)라고 하는 유일한유일한 시작시작 노드노드를 가지며,

트리는 재귀재귀 구조구조(recursive structure)이다.

각 노드를 기준으로 그 노드가 루트가 되는 부분트리부분트리(subtree)를

단점을 해결하는 한 가지 방법은 트리(tree) 구조를 사용하는 것이다. 트리는 루트(root)라고

서 각 노드까지의 경로(path)가 유일해야 하는 구조이다. 노드 A에서 노드 B까지의 경로란

노드 A와 노드 B를 연결하는 간선들에 의해 인접한 일련의 노드들의 집합을 말한다. 트리

분 트리(subtree)라 한다.

subtree (부분 트리)

root (루트 노드)

leaf node (단말 노드)

트리가 아님 Æ 그래프

internal node, intermediate node (중간 노드, 내부 노드)

루트 노드(root node): 부모가 없는 유일한 노드

단말 노드(leaf node): 자식이 없는 노드

중간 노드(internal node): 단말 노드를 제외한 모든 노드

형제 노드(sibling node): 부모가 같은 노드

조상 노드(ancestor node): 노드에서 루트 노드까지 경로 상에 있는

후손 노드(descendant node): 노드에서 단말 노드까지 경로 상에

일하게 부모 노드가 없다. 또한 자식이 없는 노드를 단말 노드(leaf node)라 하며, 단말 노

포화 이진 트리(full binary tree):

완전 이진 트리(complete binary tree):

단말 노드의 수가 n 이면 전체 노드의 수는 N =2 n -1 이다.

2 일 때 단말 노드의 수가 n 이면 전체 노드의 수는 N =2 n -1 이다.

가지는 트리를 포화 이진 트리(full binary tree)라 한다. 또한 마지막 레벨을 제외하면 포화

를 완전 이진 트리(complete binary tree)라 한다.

이진이진 검색검색 트리트리(binary search tree)란

left subtree

right subtree

이진 검색 트리(binary search tree)란 각 노드의 키 값이 왼쪽 자손 노드들의 키 값보다는

height: 3 (^) height: 4

height: 9 편향 이진 트리 (skewed binary tree)

순회순회(traversing): 트리에 있는 모든 노드를 방문하는 것

전위전위(preorder) 순회: 루트 노드를 방문 Æ 왼쪽 부분 트리에 있는

노드들을 방문 Æ 오른쪽 부분 트리에 있는 노드들을 방문

중위중위(inorder) 순회: 왼쪽 부분 트리에 있는 노드들을 방문 Æ 루트

노드를 방문 Æ 오른쪽 부분 트리에 있는 노드들을 방문

후위후위(postorder) 순회: 왼쪽 부분 트리에 있는 노드들을 방문 Æ

오른쪽 부분 트리에 있는 노드들을 방문 Æ 루트 노드를 방문

순회(traverse)란 구조에 있는 모든 요소를 최소 한번씩 방문하는 것을 말한다. 연결구조 방

되는 방법에는 전위(preorder), 중위(inorder), 후위(postorder) 세 가지 방법이 있다. 이들은

public class BinarySearchTree implements BST{ protected class BSTNode{ public Object info; public BSTNode left; public BSTNode right; } protected class TreeIterator implements Iterator{ LinkedQueue traverseQueue; public TreeIterator(int type){…} public boolean hasNext(){…} public Object next(){…} public void remove(){…} private void preOrder(BSTNode node){…} private void inOrder(BSTNode node){…} private void postOrder(BSTNode node){…} } protected BSTNode root = null; protected int numOfNodes = 0; public BinarySearchTree(){} public boolean isEmpty(){ return (root==null); } public boolean isFull(){ return false; } void clear() { … } public int numOfNodes(){ return numOfNodes; } public boolean search(Object item){…} public Object retrieve(Object item){…} public void insert(Object item){…} public boolean delete(Object item){…} public Iterator iterator(int type){ return new TreeIterator(type); } }

node.left node.right

node.info

트리의 각 노드를 나타내기 위해 BSTNode라는 내부 클래스를 사용한다. BSTNode 클래스

는 7 장에서 사용한 ListNode와 달리 두 가지 연결을 나타내는 멤버변수가 필요하다. left는

노드의 왼쪽 자식을 가리키는 멤버변수이고, right는 노드의 오른쪽 자식을 가리키는 멤버

변수이다. TreeIterator는 순회할 때 사용할 수 있는 반복자 클래스이다.

NumOfNodes 재귀적 방법으로

public int size(){ return size(root); }

private int size(BSTNode node){ if(node == null) return 0; // leaf node else return(size(node.left)+size(node.right)+1); }

Tip. 트리는 재귀적 구조이므로 재귀적 방법으로 구현하는 것이 쉽다.

트리에 있는 노드의 개수는 삽입할 때마다 증가하고 삭제될 때마다 감소하는 numOfNodes

NumOfNodes 비재귀적 방법으로

count = 0; 트리가 empty가 아니면 다음을 스택스택을 하나 생성 루트 노드를 스택에 push 스택이 empty가 아니면 다음을 반복 현재 노드를 스택 top에 있는 노드를 가리키도록 함 스택에서 노드를 하나 pop한 다음에 count를 1 증가 만약 현재 노드가 왼쪽 자식이 있으면 그 자식을 스택에 push 만약 현재 노드가 오른쪽 자식이 있으면 그 자식을 스택에 push return count;

E

C F E

A

C

F

A

public boolean search(Object item){ if(isEmpty()) throw new TreeUnderflowException(“…”); if(item==null) throw new NullPointerException(“…”); Comparable x = (Comparable)item; return search(x, root); }

private boolean search(Comparable item, BSTNode node){ if(node == null) return false; int comp = item.compareTo(node.info); if(comp<0) return search(item, node.left); else if(comp>0) return search(item, node.right); else return true; }

search 재귀 방법으로

insert

public void insert(Object item){ if(item==null) throw new NullPointerException(“…”); Comparable x = (Comparable)item; root = insert(x, root); } private BSTNode insert(Comparable item, BSTNode node){ if(node == null){ BSTNode newNode = new BSTNode(); newNode.info = item; newNode.left = null; newNode.right = null; numOfNodes++; return newNode; } int comp = item.compareTo(node.info); if(comp<0) node.left = insert(item, node.left); else if(comp>0) node.right = insert(item, node.right); else node.info = item; return node; }

delete

delete(8)

delete(2)

삭제할 노드의 부모 노드의 연결 중 삭제할 노드에 대한 연결 값을 null 값으로 바꾸면 된

delete – 계속

delete(9)

왼쪽 부분 트리 중 가장 큰 노드(predecessor)와 교체

  • 이 노드는 항상 왼쪽 부분 트리의 모든 노드보다는 크고, 오른쪽 부분 트리의 모든 노드보다는 작은 노드이다. 오른쪽 부분 트리의 가장 작은 노드와 교체 가능

predecessor를 찾아 이것을 삭제할 노드의 값과 바꿈 predecessor 노드를 삭제

delete – 계속

Traverse

protected class TreeIterator implements Iterator{ LinkedQueue traverseQueue; public TreeIterator(int type){ traverseQueue = new LinkedQueue(); switch(type){ case INORDER: inOrder(root); return; case PREORDER: preOrder(root); return; case POSTORDER: postOrder(root); return; } // switch } public boolean hasNext() { return !traverseQueue.isEmpty(); } public Object next(){ return traverseQueue.deq(); } public void remove(){ return new UnsupportedOperationException(“…”); } private void preOrder(BSTNode node){ … } private void inOrder(BSTNode node){ if(node!=null){ if(node.left!=null) inOrder(node.left); traverseQueue.enq(node.info); if(node.right!=null) inOrder(node.right); } } private void postOrder(BSTNode node){ … } }

O(N) O(1) O(N)

O(log 2 N) O(N) O(N)

O(log 2 N) O(log 2 N) O(log 2 N)

delete Find process Total

O(N) O(1) O(N)

O(log 2 N) O(N) O(N)

O(log 2 N) O(1) O(log 2 N)

insert Find process Total

O(N) O(1) O(N)

O(log 2 N) O(1) O(log 2 N)

O(log 2 N) O(1) O(log 2 N)

retrieve Find process Total

search O(log 2 N) O(log 2 N) O(N)

constructor O(1) O(N) O(1)

BST* 배열 리스트 연결 리스트

*. 균형 트리일 경우에만 O(log 2 N)

단계단계^ 1.1.^ 트리 정보를 배열에 저장한 다음에

세 가지 방법: inorder, preorder, postorder

단계단계^ 2.2.^ 이 정보를 이용하여 트리를 재구성

postorder: 3 7 8 5 12 10

inorder

preorder

postorder

preorder: 10 5 3 8 7 12

inorder: 3 5 7 8 10 12