Skip to content

Instantly share code, notes, and snippets.

@thomas-holmes
Last active May 9, 2019 01:20
Show Gist options
  • Save thomas-holmes/308f9e44f1a46461762a35056818774a to your computer and use it in GitHub Desktop.
Save thomas-holmes/308f9e44f1a46461762a35056818774a to your computer and use it in GitHub Desktop.
trees
#include "stdafx.h"
#include <iostream>
#include <string>
#include "tree.hh"
#include "tree_util.hh"
using namespace std;
int main()
{
tree<string> tr;
tree<string>::iterator top, one, two, loc, banana;
top = tr.begin();
one = tr.insert(top, "one");
two = tr.append_child(one, "two");
tr.append_child(two, "apple");
banana = tr.append_child(two, "banana");
tr.append_child(banana, "cherry");
tr.append_child(two, "peach");
tr.append_child(one, "three");
cout << "printing bracketed tree:" << endl;
kptree::print_tree_bracketed(tr);
cout << endl << endl;
cout << "printing leaf nodes and appending a child to each one:" << endl;
tree<string>::leaf_iterator iter = tr.begin_leaf();
while (tr.is_valid(iter)) {
cout << *(tr.parent(iter)) << " > " << (*iter) << endl;
// Capture the current iterator location for appending children
tree<string>::leaf_iterator append_iter = iter;
// advance your real iterator to the next node before adding children
iter++;
// Loop and append new children
for (int i = 0; i < 3; i++) {
tr.append_child(append_iter, "child" + to_string(i));
}
}
cout << endl << "-------" << endl << endl << "printing tree with new children:" << endl;
kptree::print_tree_bracketed(tr);
cout << endl << endl << "Printing leaf nodes" << endl << endl;
iter = tr.begin_leaf();
while (tr.is_valid(iter)) {
cout << *(tr.parent(iter)) << " > " << (*iter) << endl;
iter++;
}
return 0;
}
printing bracketed tree:
one(two(apple, banana(cherry), peach), three)
printing leaf nodes and appending a child to each one:
two > apple
banana > cherry
two > peach
one > three
-------
printing tree with new children:
one(two(apple(child0, child1, child2), banana(cherry(child0, child1, child2)), peach(child0, child1, child2)), three(child0, child1, child2))
Printing leaf nodes
apple > child0
apple > child1
apple > child2
cherry > child0
cherry > child1
cherry > child2
peach > child0
peach > child1
peach > child2
three > child0
three > child1
three > child2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment