According to the Homespring proposed language standard, salmon travelling upstream need to perform "an in-order search of the river system … to find a river node with the same name as the salmon" on the fish tick up (section 6.4.2). The problem is that the river nodes are stored in an n-ary tree, so I'm unsure of how to conduct an in-order search of this tree. A Google search brought up nothing relevant and the Wikipedia page does not even mention any sort of traversal. Is it possible to traverse a k-ary tree in-order?
Yes, it is indeed possible to do this! Let's reason by analogy. In a binary tree, a node looks like this:
+---+
| v |
+---+
/ \
T0 T1
An inorder traversal is then done as follows:
In other words, you can imagine sweeping from left to right visiting values as you find them. The sweep first hits T0, then hits v, then hits T1.
A node in a multiway tree looks like this:
+----+----+----+ ... +----+
| v0 | v1 | v2 | ... | vn |
+----+----+----+ ... +----+
/ | | | | \
T0 T1 T2 T3 Tn Tn+1
If we use the "sweep from left to right" idea here, we'd do this:
Here's some pseudocode for this:
void inorderWalk(Node* v) {
if (v == null) return;
for (int i = 0; i < v.numChildren; i++) {
inorderWalk(v.child[i]);
visit(v.value[i]);
}
inorderWalk(v.child[v.numChildren]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With