Skip to content

Instantly share code, notes, and snippets.

@svenoaks
Last active August 29, 2015 14:10
Show Gist options
  • Save svenoaks/01aac530df31b08951a6 to your computer and use it in GitHub Desktop.
Save svenoaks/01aac530df31b08951a6 to your computer and use it in GitHub Desktop.
preorder traversal using custom function
//
// main.cpp
// preorder
//
// Created by Steve Myers on 11/20/14.
#include <iostream>
#include <array>
#include "binarySearchTree.h"
template<typename T>
class binaryTreeFuncTraverse : public bSearchTreeType<T>
{
template<typename Func>
void preorder(binaryTreeNode<T> *p, Func func) const
{
if (p != NULL)
{
func(p->info);
preorder(p->llink, func);
preorder(p->rlink, func);
}
}
public:
template<typename Func>
void preorderTraversal(Func func)
{
preorder(this->root, func);
};
};
int main()
{
const array<int, 8> testItems { 1, 10, 34, 56, 23, 11, 4, 15 };
binaryTreeFuncTraverse<int> tree;
for (const auto& item : testItems) tree.insert(item);
int total = 0;
tree.preorderTraversal( [&](const int& m) {
total += m;
});
cout << "Total of all items in tree: " << total << endl;
tree.preorderTraversal( [](int& m) {
m = m * m;
});
cout << "Items in tree after squaring: " << endl;
tree.preorderTraversal( [](const int& m) {
cout << m << " ";
});
//OUTPUTS:
// Total of all items in tree: 154
// Items in tree after squaring:
// 1 100 16 1156 529 121 225 3136
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment