Suppose we have a tree (not necessary a binary tree) with the root node is labeled 1. How to know the the exact number of tree with the same DFS order?
For example, if we have the DFS traversal: {1, 2, 3}, then the answer is 2, because we have two trees: {(1, 2), (2, 3)} and {(1, 2), (1, 3)}
I'm curious about how we can count it efficiently with the maximum number of nodes <= 100. I appreciate for your help!!
Edit: Another thing I missed is that this DFS order is not totally random. It ensures that if there are several nodes with different values, it will call those nodes in ascending order. Consider this pseudocode in python for more detail:
def dfs(u):
print(u)
vis[u] = true
for i in range(1,n + 1):
if i in adj(u) and vis[i] == false:
dfs(i)
I've found out the solution for this, fortunately. However, thanks for all of you to take time for this.
The actual problem required to get the answer in modulo 10 ^ 9 + 7, so generating all the possible tree is not a good idea, since the number will be big. Instead, we will look at the order of DFS to decide how we can construct this tree.
Consider the case the DFS is [1,2,4,3]. If you try to draw all 3 trees that appropriate to this order, you will see the pattern. Specifically, there's no such tree like {(1, 2), (1, 4), (1, 3)}, because if it is, the order will be [1,2,3,4]. As you can see, if you consider (1,4) as an edge, then you must immediately take (4,3) as the next edge, otherwise the DFS order will call the node 3 before calling the node 4. Another thing is that, if some nodes are in a same subtree, then in the DFS order they will be adjacent.
This is my whole observation. Now, to calculate the answer, I will consider how I will divide the array into the subtree. Let's consider a bigger input, like [1,2,4,5,7,3,8,6]. 1 will be the root, so we will ignore it. For the rest, I will decide how I divide the nodes into subtree, then there will be several ways. These are some possible ways to divide them: {(2,4), (5,7,3,8,6)}, {(2,4,5), (7,3,8,6)}, {(2), (4), (5), (7), (3), (8), (6)} (as I draw below). Note that, division likes {(2), (4,5,7), (3,8,6)} is not valid as the root of the second subtree is 4, which is larger than the root of the third subtree (4 > 3), and it will not obey the initial DFS order as 3 will be called before 4. After we have divided nodes that connect to the root 1, the only thing we have to do now is recursively calculate the number of valid tree in each subtree, then multiply them together to get the answer.
As there will be many overlaps, we can use DP to optimize the solution above. The time complexity is hard for me to estimate, since I don't know how to calculate the complexity when dividing the array into subtree. However, I run with n = 100 and it looks fast, so it's fine.