Ranking AVL trees

Given a non-empty binary tree TT, let TLT_L and TRT_R denote respectively the left child of TT and the right child of TT. A binary tree TT is an AVL tree if and only if TT is empty, or TLT_L and TRT_R are AVL trees such that |height(TL)height(TR)|1\vert \mbox{height}(T_L) - \mbox{height}(T_R) \vert \le 1. These are some examples of AVL trees with respective heights 0, 1, 2, 2, 2, 3 and 3 (a box denotes an empty tree):

image

We can inductively define a total order over AVL trees as follows: The empty tree is the smallest AVL tree. For every two non-empty AVL trees AA and BB, A<BA < B if and only if

The trees in the picture above are the first, second, ... , seventh AVL trees using this order.

Write a program such that, for every given AVL tree, computes and prints its rank (that is, its position in the infinite sorted list of AVL trees, starting at 1).

Input

Input begins with the number of cases nn, followed by nn strings, each one with the preorder of an AVL tree, with ‘1’ denoting a node and ‘0’ denoting a leaf. No given tree has height larger than 6.

Output

For every given AVL tree, print its rank.

Problem information

Author: Salvador Roura

Generation: 2026-01-25T10:10:18.627Z

© Jutge.org, 2006–2026.
https://jutge.org