diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-13 22:29:59 +0100 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-13 22:29:59 +0100 |
commit | c64d8fdb9016263b82207d265def04589fb6f22b (patch) | |
tree | 41dcd3449cd574637d527aedd04b975dc406bc6c /02-data_structures/04-binary_search_trees/01-tree_orders | |
parent | f14c9988786b578c115ba1f8a93d61f51d013e2f (diff) | |
download | coursera-c64d8fdb9016263b82207d265def04589fb6f22b.zip coursera-c64d8fdb9016263b82207d265def04589fb6f22b.tar.gz |
Algorithms : complete 02-data_structures 04-binary_search_trees
Diffstat (limited to '02-data_structures/04-binary_search_trees/01-tree_orders')
-rw-r--r-- | 02-data_structures/04-binary_search_trees/01-tree_orders/tree-orders.cpp | 43 |
1 files changed, 34 insertions, 9 deletions
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 <int> in_order() { vector<int> result; - // Finish the implementation - // You may need to add a new recursive method to do that + in_order_visit(0, result); return result; } vector <int> pre_order() { - vector<int> result; - // Finish the implementation - // You may need to add a new recursive method to do that - + vector<int> result; + pre_order_visit(0, result); + return result; } vector <int> post_order() { vector<int> 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<int> &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<int> &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<int> &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 <int> a) { |