From c64d8fdb9016263b82207d265def04589fb6f22b Mon Sep 17 00:00:00 2001 From: Jérémy Zurcher Date: Sun, 13 Nov 2016 22:29:59 +0100 Subject: Algorithms : complete 02-data_structures 04-binary_search_trees --- .../01-tree_orders/tree-orders.cpp | 43 +++++++++++++++++----- 1 file changed, 34 insertions(+), 9 deletions(-) (limited to '02-data_structures/04-binary_search_trees/01-tree_orders') diff --git a/02-data_structures/04-binary_search_trees/01-tree_orders/tree-orders.cpp b/02-data_structures/04-binary_search_trees/01-tree_orders/tree-orders.cpp index 5ee679c..d9437fa 100644 --- a/02-data_structures/04-binary_search_trees/01-tree_orders/tree-orders.cpp +++ b/02-data_structures/04-binary_search_trees/01-tree_orders/tree-orders.cpp @@ -27,27 +27,52 @@ public: vector in_order() { vector result; - // Finish the implementation - // You may need to add a new recursive method to do that + in_order_visit(0, result); return result; } vector pre_order() { - vector result; - // Finish the implementation - // You may need to add a new recursive method to do that - + vector result; + pre_order_visit(0, result); + return result; } vector post_order() { vector result; - // Finish the implementation - // You may need to add a new recursive method to do that - + post_order_visit(0, result); + return result; } +private: + + void in_order_visit(int n, vector &r) + { + if (left[n] != -1) + in_order_visit(left[n], r); + r.push_back(key[n]); + if (right[n] != -1) + in_order_visit(right[n], r); + } + + void pre_order_visit(int n, vector &r) + { + r.push_back(key[n]); + if (left[n] != -1) + pre_order_visit(left[n], r); + if (right[n] != -1) + pre_order_visit(right[n], r); + } + + void post_order_visit(int n, vector &r) + { + if (left[n] != -1) + post_order_visit(left[n], r); + if (right[n] != -1) + post_order_visit(right[n], r); + r.push_back(key[n]); + } }; void print(vector a) { -- cgit v1.2.3