I have a vector based binary tree and need to apply a function to each value in the tree using various methods of traversal. The preorder traversal was very easy to implement with a recursive function but I have been having trouble doing the same with the inorder and postorder traversals. If anyone could help out that would be great!
Some extra information that I should have included:
I am using a vector of nodes, each node containing a boolean variable stating whether or not that node is filled and a templated data variable. Each node is stored at an index “i” while its left child is at the index “2i+1” and the right child at “2i+2”.
To apply a preorder traversal to the list, I first processed the data stored at index 0 and then called this recursive function
template <typename Item, typename Key>
template <typename Function>
void BST<Item,Key>::preTraverse(int n, Function f) {
if(tree[n].occupied == false) return;
else {
f(tree[n].data);
preTraverse(2*i+1,f);
preTraverse(2*i+2,f);
}
}
twice beginning with indices 1 & 2 as my “n” parameter.
Assuming your tree is a max-populated left-dominant representation, then any given point in your array at position
iwill have children at positions2*i+1and2*i+2. The trivial walk:Given this definition, preorder, postorder, and in-order can all be done with simple index forwarding and some checks for your ‘occupied’ flag. The following templates assume type
Tis a structure type that has an ‘occupied’ member.