๋ฐ์ํ
์๋์ ์์์ ๋ฐํ์ผ๋ก ์์ฑ๋์์ต๋๋ค. ์ข์์์ ๊ฐ์ฌํฉ๋๋ค.
[์๋ฃ๊ตฌ์กฐ ์๊ณ ๋ฆฌ์ฆ] ์ด์งํธ๋ฆฌ๋ฅผ ๋ ๋ฒจ๋จ์ ๋ฆฌ์คํธ๋ก ๋ณํํ๊ธฐ
https://youtu.be/Y9Ar9eerxQU
(1) .h
์ฝ๋1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <iostream> | |
#include <algorithm> | |
#include <vector> | |
#include <queue> | |
using namespace std; | |
class Node | |
{ | |
public: | |
int data; | |
Node* left, * right; | |
Node(int data) { | |
this->data = data; | |
this->left = this->right = NULL; | |
} | |
}; | |
class Tree | |
{ | |
public: | |
Node* root = NULL; | |
vector <vector<Node*>> levels; | |
Tree(vector<int> a) | |
{ | |
root = bst(a, 0, a.size() - 1); | |
} | |
Node* bst(vector<int> a, int start, int end) | |
{ | |
if (start <= end) | |
{ | |
int mid = (start + end) / 2; | |
Node* newNode = new Node(a[mid]); | |
newNode->left = bst(a, start, mid - 1); | |
newNode->right = bst(a, mid + 1, end); | |
return newNode; | |
} | |
return NULL; | |
} | |
void bstToList1()//solutoin1.level๊ณผ ์ฌ๊ท๋ฅผ ์ด์ฉ | |
{ | |
levels.clear(); | |
traversal1(levels, root, 0); | |
} | |
void traversal1(vector <vector<Node*>>& lists, Node* node, int level) | |
{ | |
if (node == NULL) return; | |
vector<Node*> list; | |
if (lists.size()==level){ | |
list.push_back(node); | |
lists.push_back(list); | |
} | |
else | |
lists[level].push_back(node); | |
traversal1(lists, node->left, level + 1); | |
traversal1(lists, node->right, level + 1); | |
} | |
void bstToList2()//solution2. bfs๋ณํ์ ์ด์ฉ | |
{ | |
levels.clear(); | |
levels= traversal2(root); | |
} | |
vector <vector<Node*>> traversal2(Node* node) | |
{ | |
vector<vector<Node*>> result; | |
vector<Node*>current; | |
if (node != NULL) current.push_back(node); | |
result.push_back(current); | |
while (!current.empty()){ | |
vector<Node*>parent = current; | |
current.clear(); | |
for (int i = 0; i < parent.size(); i++) | |
{ | |
if (parent[i]->left) current.push_back(parent[i]->left); | |
if (parent[i]->right) current.push_back(parent[i]->right); | |
} | |
if(!current.empty()) result.push_back(current); | |
} | |
return result; | |
} | |
void print()//๋ ๋ฒจ๋ณ ๋ฆฌ์คํธ ์ถ๋ ฅ | |
{ | |
for (int i = 0; i < levels.size(); i++) | |
{ | |
for (int j = 0; j < levels[i].size(); j++) | |
cout << levels[i][j]->data << " "; | |
cout << endl; | |
} | |
} | |
}; |
(2) .cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "header.h" | |
int main() { | |
//์ ๋ ฌ ๋์ด์๋ ๋ฐฐ์ด์ ๋ฃ๋๋ค | |
Tree* t = new Tree({ 0,1,2,3,4,5,6,7,8,9 }); | |
t->bstToList2(); | |
t->print(); | |
return 0; | |
} |
๋ฐ์ํ