I have an AVL tree and I need to traverse it in ascending and descending order.
I implemented a simple algorithm, where knowing the tree size in advance, I allocate an array and assign 0
to a counter, then I traverse the tree as follows:
void traverseAscending(Node cur) {
if(cur.left != null) traverseAscending(cur.left);
outVals[totOuts] = cur.data;
totOuts++;
if(cur.right != null) traverseAscending(cur.right);
}
This is the classics we've all been taught. However, it's slow likely because the branches are mispredicted all the time.
How to traverse the tree in a way friendly for branch predictor?
UPDATE: answering the comments,
- I came to the conclusion that it's branching that is slow because I profiled the application.
- The cache should not be an issue because I have multiple relatively small trees that fit the cache.
- Indeed, the share of this method in the profiler decreases over time, but I would think it's because the algorithm changes so the bottlenecks change. The first ~10 minutes of running this method takes ~6% of the runtime.