#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<vector> #include<cmath> #include<map> #include<string> #include<set> #include<queue> using namespace std; typedef long long LL; const int INF=0x7f7f7f7f; const int inf=0x80808080; struct TreeNode { int val; TreeNode *left,*right; TreeNode(int x):val(x),left(NULL),right(NULL) {} }; void read(TreeNode **node) { int x; scanf("%d",&x); if(x==0) *node=NULL; else { *node=new TreeNode(x); read(&(*node)->left); read(&(*node)->right); } } void GetSortedList(TreeNode *node,TreeNode **beg,TreeNode **end) { if(node->left==NULL&&node->right==NULL) *beg=node,*end=node; else { TreeNode *begL=NULL,*endL=NULL; if(node->left!=NULL) { GetSortedList(node->left,&begL,&endL); endL->right=node; node->left=endL; *beg=begL; } else *beg=node; TreeNode *begR=NULL,*endR=NULL; if(node->right!=NULL) { GetSortedList(node->right,&begR,&endR); begR->left=node; node->right=begR; *end=endR; } else *end=node; } } TreeNode* TreeToSortedList(TreeNode *root) { if(root==NULL) return NULL; TreeNode *beg=NULL,*end=NULL; GetSortedList(root,&beg,&end); return beg; } void out(TreeNode *root) { while(root!=NULL) { printf("%d ",root->val); root=root->right; } } void erase(TreeNode *node) { while(node!=NULL) { TreeNode *temp=node; node=node->right; delete temp; } } int main() { int n; scanf("%d",&n); while(n--) { TreeNode *root; read(&root); TreeNode *newroot=TreeToSortedList(root); out(newroot); printf("\n"); erase(root); } return 0; }