
#include <bits/stdc++.h>
using namespace std;

// Creating a struct Node.
struct Node
{
    int data;
    Node* left;
    Node* right;
};

// Function to create a new Tree Node
Node* newNode(int val)
{
    Node* a = new Node;
    a>data = val;
    a->left = NULL;
    a->right = NULL;

    return a;
}


Node* buildTree(string str)
{
    // Corner Case
    if (str.length() == 0 || str[0] == 'N')
        return NULL;

    // Creating vector of strings from input
    // string after spliting by space
    vector<string> ip;

    istringstream iss(str);
    for (string str; iss >> str; )
        ip.push_back(str);

    The root of the tree is created
    Node* root = newNode(stoi(ip[0]));

     Root is pushed to the queue
    queue<Node*> queue;
    queue.push(root);

    // Starting from the second element
    int i = 1;
    while (!queue.empty() && i < ip.size()) {

        // Get and remove the front of the queue
        Node* currNode = queue.front();
        queue.pop();

        // Get the current node's value from the string
        string currVal = ip[i];

        // If the left child is not null
        if (currVal != "N") {

            // Create the left child for the current node
            currNode->left = newNode(stoi(currVal));

            // Push it to the queue
            queue.push(currNode->left);
        }

        // For the right child
        i++;
        if (i >= ip.size())
            break;
        currVal = ip[i];

        // If the right child is not null
        if (currVal != "N") {

            // Create the right child for the current node
            currNode->right = newNode(stoi(currVal));

            // Push it to the queue
            queue.push(currNode->right);
        }
        i++;
    }

    return root;
}


 // } Driver Code Ends


class Solution
{
    public:
 
    vector<int>topView(Node *root){
        
      vector<int>v;
      
      if(root==NULL)
       return v;
       
     map<int,int>mp,visited;
    
     map<int,int>::iterator it;
     queue<pair<Node*,int>>q;
     
     q.push({root,0});
     int x;
   // visited[0]=1;

     
     while(!q.empty()){
       Node*node=q.front().first;  
       x=q.front().second;
       q.pop();
       
       if(visited[x]==0){
       mp[x]=node->data;
       visited[x]=1;
       }
       
       if(node->left!=NULL){
           q.push({node->left,x-1});
       }
       if(node->right!=NULL){
           q.push({node->right,x+1});
       }
     }
     
     for(it=mp.begin();it!=mp.end();it++)
       v.push_back(it->second);
       
       
     
     return v; 
    }

};



// { 

int main() {
    int tc;
    cin>>tc;
    cin.ignore(256, '\n');
    while (tc--) {
        string treeString;
        getline(cin, treeString);
        Solution ob;
        Node *root = buildTree(treeString);
        vector<int> vec = ob.topView(root);
        for(int x : vec)
            cout<<x<<" ";
        cout<<endl;
    }
    return 0;
} 