Binary Search Tree
Time limit2sMemory limit256 MB
Count the insertion orders that build the same binary search tree as the given permutation.
- Level
Medium6 of 10
- Topics
- Combinatorics, Tree, Recursion
- Solved
- No attempts yet
Problem
A binary search tree is a binary tree, and it may be empty. A non-empty binary search tree satisfies the following properties.
- Every node holds a distinct key.
- Every key in the left subtree of a node is smaller than that node's key.
- Every key in the right subtree of a node is larger than that node's key.
- The left subtree and the right subtree are themselves binary search trees.
Searching for a key in a binary search tree works as follows. Start at the root; if is empty, the search fails. Otherwise, compare with the root's key. If they are equal, the search succeeds. If is smaller than the root's key, continue in the left subtree; if it is larger, continue in the right subtree.
To insert a new key that is not already in , first search for in . Since is not present, the search fails, and is inserted as a new node at the empty spot where the search stopped.
In this problem we work with binary search trees whose keys are . Given a permutation of , inserting through in order into an empty tree produces one binary search tree.
Different permutations may produce the same tree. For example, inserting the permutation in order builds the tree whose root is with left child and right child , where has left child and right child . The permutation builds exactly the same tree. Among all permutations of , there are that build this tree.
Given and a permutation , write a program that counts how many permutations build the same binary search tree as .
Input
The first line contains the number of test cases ().
Each test case consists of two lines. The first line contains the number of keys (), and the second line contains a permutation of of length , separated by spaces.
Output
For each test case, print on its own line the number of permutations that build the same binary search tree as the given permutation, modulo .