summaryrefslogtreecommitdiffstats
path: root/02-data_structures/01-basic_data_structures/02-tree_height/tree-height.cpp
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2016-11-13 21:53:09 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-13 21:53:09 +0100
commitc6c693c11aa3726535522d4032f150570715fa6a (patch)
tree51b5bc3b37a1fac0fa920deb9a1362c56dc60597 /02-data_structures/01-basic_data_structures/02-tree_height/tree-height.cpp
parentad7fd3dccdcd1baefcb637a599bcfa699550c7f5 (diff)
downloadcoursera-c6c693c11aa3726535522d4032f150570715fa6a.zip
coursera-c6c693c11aa3726535522d4032f150570715fa6a.tar.gz
Algorithms : add 02-data_structures 01-basic_data_structures
Diffstat (limited to '02-data_structures/01-basic_data_structures/02-tree_height/tree-height.cpp')
-rw-r--r--02-data_structures/01-basic_data_structures/02-tree_height/tree-height.cpp35
1 files changed, 35 insertions, 0 deletions
diff --git a/02-data_structures/01-basic_data_structures/02-tree_height/tree-height.cpp b/02-data_structures/01-basic_data_structures/02-tree_height/tree-height.cpp
new file mode 100644
index 0000000..d050e88
--- /dev/null
+++ b/02-data_structures/01-basic_data_structures/02-tree_height/tree-height.cpp
@@ -0,0 +1,35 @@
+#include <iostream>
+#include <vector>
+#include <algorithm>
+
+class TreeHeight {
+ int n;
+ std::vector<int> parent;
+
+public:
+ void read() {
+ std::cin >> n;
+ parent.resize(n);
+ for (int i = 0; i < n; i++)
+ std::cin >> parent[i];
+ }
+
+ int compute_height() {
+ // Replace this code with a faster implementation
+ int maxHeight = 0;
+ for (int vertex = 0; vertex < n; vertex++) {
+ int height = 0;
+ for (int i = vertex; i != -1; i = parent[i])
+ height++;
+ maxHeight = std::max(maxHeight, height);
+ }
+ return maxHeight;
+ }
+};
+
+int main() {
+ std::ios_base::sync_with_stdio(0);
+ TreeHeight tree;
+ tree.read();
+ std::cout << tree.compute_height() << std::endl;
+}