diff --git a/algorithm/graph_algorithm.cpp b/algorithm/graph_algorithm.cpp new file mode 100644 index 0000000..6630fd2 --- /dev/null +++ b/algorithm/graph_algorithm.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include + +template +struct graph { +public: + graph(int v_num):v(v_num) { + edge = std::vector>(v_num); + indegree = std::vector(v_num, 0); + } + + void addEdge(int from, int to) { + edge[in].push_back(to); + indegree[to]++; + } + + int v; + vector indegree; + std::vector> edge; + +} + +template +void topological_sorting(graph g) { + std::queue q; + + for (int i = 0; i < g.indegree.size(); ++i ) { + if (g.indegree[i] == 0) { + q.push[i]; + } + } + + while(!q.empty()) { + int v = q.top() + std::cout << v << std::endl; + q.pop(); + for (auto i = g.edge[v].begin(); i != g.edge[v].end(), ++i) { + g.indegree[*i]--; + if (g.indegree[*i] == 0) q.push(*i); + } + } + return; +} + +int main() { +} diff --git a/algorithm/tree_algorithms.cpp b/algorithm/tree_algorithms.cpp new file mode 100644 index 0000000..d9dac5c --- /dev/null +++ b/algorithm/tree_algorithms.cpp @@ -0,0 +1,105 @@ +#include +#include +#include + +template +struct node { +public: + node():left(nullptr), right(nullptr) {} + T value; + node * left; + node * right; +}; + +template +void DLR(node * root) { + std::stack *> stack; + stack.push(root); + + node * top; + while(!stack.empty()) { + top = stack.top(); + std::cout << top->value << std::endl; + stack.pop(); + if (top->right != nullptr) stack.push(top->right); + if (top->left != nullptr) stack.push(top->left); + } + return; +}; + +template +void LDR(node * root) { + std::stack *> stack; + while(root != nullptr || !stack.empty()) { + while(root != nullptr) { + stack.push(root); + root = root->left; + } + if(!stack.empty()){ + root = stack.top(); + std::cout << root->value << std::endl; + stack.pop(); + root = root->right; + } + } + return; +}; + +template +void LRD(node * root) { + if (root == nullptr) return; + std::stack *> stack; + stack.push(root); + + node * last_pop = nullptr; + while(!stack.empty()) { + while(root->left != nullptr) { + root = root->left; + stack.push(root); + } + while(!stack.empty()) { + if (root->right == nullptr || root->right == last_pop) { + std::cout << root->value << std::endl; + stack.pop(); + last_pop = root; + if (!stack.empty()){ + root = stack.top(); + } + } else { + root = root->right; + stack.push(root); + break; + } + } + } + return; +}; + +/* + 1 + / \ + 2 3 + \ + 4 + / + 5 +*/ + +int main() { + node * root = new node(); + root->value = 1; + root->left = new node(); + root->left->value = 2; + root->right = new node(); + root->right->value = 3; + root->left->right = new node(); + root->left->right->value = 4; + root->left->right->left = new node(); + root->left->right->left->value = 5; + + DLR(root); + LDR(root); + LRD(root); + + return 0; +}