트리 순회
모든 노드를 한번씩 가는 방법에 대해 알아봅시다.
- Breadth - first Search (BFS) 맞는지 확인하기
- F- B - G - A - D - I - C - E - H
- Depth - first Search (DFS) 맞는지 확인하기
- IN Order : A B C D E F G H I
- Preorder : F B A D C E G I H
- Post Order : A C E D B H I G F
- 너비 우선 서칭 루트 노드(혹은 다른 임의의 노드)에서 시작해서 인접한 노드를 먼저 탐색하는 방법
루트 노드(혹은 다른 임의의 노드)에서 시작해서 인접한 노드를 먼저 탐색하는 방법
- 큐(First In First Out)를 만들고 방문한 노드를 담을 변수를 만듭니다.
- 큐를 root 노드에 위치 시킵니다.
Loop큐에 아무것도 없을때 까지- Dequeue a node from the queue and push the value of the node into the variable that stores the nodes
- If there is a left property on the node dequeued - add it to the queue
- If there is a right property on the node dequeued - add it to the queue
- Return the variable that stores the values
BFS() {
const data = [],
queue = [];
let node = this.root;
queue.push(this.root);
while (queue.length) {
node = queue.shift();
data.push(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return data;
}- 방문한 노드를 담을 변수를 만듭니다.
- BST의 루트를 저장할 current란 변수를 만듭니다.
- 노드를 받을 helper function을 만듭니다.
- 노드의 value를 값을 저장하는 변수에 Push 합니다.
if 노드의 왼쪽 프로퍼티가 존재한다면,왼쪽 노드 프로퍼티에 helper 함수를 부릅니다.if 노드의 오른쪽 프로퍼티가 존재한다면,오른쪽 노드 프로퍼티에 helper 함수를 부릅니다.
- 현재 값과 helper 함수를 불러옵니다.
- array를 리턴합니다.
- 방문한 노드를 담을 변수를 만듭니다.
- BST의 루트를 저장할 current란 변수를 만듭니다.
- 노드를 받을 helper function을 만듭니다.
if 노드의 왼쪽 프로퍼티가 존재한다면,왼쪽 노드 프로퍼티에 helper 함수를 부릅니다.if 노드의 오른쪽 프로퍼티가 존재한다면,오른쪽 노드 프로퍼티에 helper 함수를 부릅니다.- 노드의 value를 값을 저장하는 변수에 Push 합니다.
- current 변수에 helper function을 불러옵니다
- array를 return 합니다.
- 방문한 노드를 담을 변수를 만듭니다.
- BST의 루트를 저장할 current란 변수를 만듭니다.
- 노드를 받을 helper function을 만듭니다.
if 노드의 왼쪽 프로퍼티가 존재한다면,왼쪽 노드 프로퍼티에 helper 함수를 부릅니다.- 노드의 value를 값을 저장하는 변수에 Push 합니다.
if 노드의 오른쪽 프로퍼티가 존재한다면,오른쪽 노드 프로퍼티에 helper 함수를 부릅니다.
- current 변수에 helper function을 불러옵니다
- array를 return 합니다.
DFSPreOrder() {
const date = [];
function traverse(node) {
date.push(node.value);
node.left && traverse(node.left);
node.right && traverse(node.right);
}
traverse(this.root);
return date;
}
DFSPostOrder() {
const data = [];
function traverse(node) {
node.left && traverse(node.left);
node.right && traverse(node.right);
data.push(node.value);
}
traverse(this.root);
return data;
}
DFSInOrder() {
const data = [];
function traverse(node) {
node.left && traverse(node.left);
data.push(node.value);
node.right && traverse(node.right);
}
traverse(this.root);
return data;
}- 두 노드 사이의 최단 경로와 임의의 경로를 찾고 싶을 때 사용
- DFS-IN Order
[ 3, 6, 8, 10, 15, 20 ]- 작은수에서 큰수로 정렬된 값을 얻을 때 사용합니다.
- DFS - Pre Order
[ 10, 6, 15, 3, 8, 20 ]- Tree 구조 그대로 가져오기 때문에 파일시스템이나 데이터베이스 정보를 저장 복사 하기 좋습니다.