Leonhard Euler wants to visit a few friends who live in houses 2, 3, ..., N (he lives in house 1). However, because of how his city is laid out, none of the paths between any houses form a loop (so, the houses exist on a graph which is a tree).
He gets bored easily but if he visits his friends in a different order, he won't be bored. So, he wants you to help him find how many unique ways there are for him to visit every friend and return home by the end of the day.
He doesn't have a map of his city, but he does remember the order of houses he visited last time he went on a walk.
Problem Statement
Given the Euler Tour Representation of a tree, determine the number of unique ETRs of the same tree, with the root at 1.
Input
The ETR of a tree. The Euler Tour Representation essentially starts at the root and traverses the tree depth-first writing out the label of each node as it goes along. A 3-node tree with one root and two children would be represented as 1 -> 2 -> 1 -> 3 -> 1
. A 3-node tree with one root, one child, and one grandchild would be represented as 1 -> 2 -> 3 -> 2 -> 1
.
In other words, it represents the Eulerian circuit of a directed graph derived from creating two edges from each edge in the tree, one in each direction.
Here is a visual example of an ETR:
I will allow a few alterations to the input:
- You can choose if you want leaf nodes to be written once or twice consecutively.
- You can choose if you want to return to the root at the end.
For example, here is a tree:
1
/ \
2 3
/ \ \
4 5 6
The following are acceptable:
1 2 4 2 5 2 1 3 6 3 1
1 2 4 2 5 2 1 3 6 3
1 2 4 4 2 5 5 2 1 3 6 6 3 1
1 2 4 4 2 5 5 2 1 3 6 6 3
(this is shown on the Wikipedia article)
You can take the input in any reasonable format for a list of integers. You may also request to input N
(the number of nodes) first, and to index at any arbitrary value (I use 1-indexing here). However, your node labels starting from x
must be x, x+1, x+2, ..., x+N-1
.
Output
An integer, representing the number of unique ETRs of this tree, starting from the same root node.
Challenge Specifications and Rules
- note that inputs are NOT always binary trees; see the second test case
- this is a code-golf problem, so scoring is by code length with a lower score being better
- no answer will be accepted
- Standard Loopholes apply
Test Cases
[1, 2, 3, 2, 4, 5, 4, 6, 4, 2, 1, 7, 8, 9, 8, 7, 1] -> 8
[1, 2, 3, 2, 4, 2, 1, 5, 6, 5, 7, 5, 1, 8, 9, 8, 10, 8, 1] -> 48
[1, 2, 3, 4, 5, 6, 7, 6, 8, 6, 5, 9, 5, 4, 10, 4, 3, 11, 3, 2, 12, 2, 1] -> 32
[1] -> 1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1] -> 1
If you want to test with more data, my reference implementation is here. It's pretty bad but it's correct so you can use it; just modify the list in line 3.