#include #include #include using namespace std; ifstream input_stream; ofstream output_stream; struct Node { public: uint32_t number; Node *left, *right; Node(uint32_t n):number(n) { } Node(): number(0) { } }; bool locateLeftmostNode (Node *node, uint32_t level, uint32_t targetLevel) { if (level == targetLevel) { cout << node -> number << " "; return 1; } else { // Search left. If unsuccessfull, search through right if (node -> left != nullptr) { if (locateLeftmostNode(node -> left, level + 1, targetLevel)) { return 1; } } // Search right. If unsuccessful, this should return 0 if (node -> right != nullptr) { return locateLeftmostNode(node -> right, level + 1, targetLevel); } // Previous searches didn't return anything, meaning node has no children. Return 0 return 0; } } bool locateRightmostNode (Node *node, uint32_t level, uint32_t targetLevel) { if (level == targetLevel) { cout << node -> number << endl; return 1; } else { // Search right. If unsuccessfull, search through left if (node -> right != nullptr) { if (locateRightmostNode(node -> right, level + 1, targetLevel)) { return 1; } } // Search left. If unsuccessful, this should return 0 if (node -> left != nullptr) { return locateRightmostNode(node -> left, level + 1, targetLevel); } // Previous searches didn't return anything, meaning node has no children. Return 0 return 0; } } int main() { input_stream.open("input.txt"); uint32_t N; uint16_t K; input_stream >> N; input_stream >> K; unordered_map orphanNodes; Node *nodes[N]; for (uint32_t i = 0; i < N; i++) { nodes[i] = new Node(i + 1); orphanNodes[i + 1] = nodes[i]; } for (uint32_t i = 0; i < (N - 1); i++) { uint32_t parentId, childId; char direction; input_stream >> parentId; input_stream >> childId; input_stream >> direction; // Remove orphan mark from child orphanNodes.erase(childId); // Assign child to parent if(direction == 'S') { nodes[parentId - 1] -> left = nodes[childId - 1]; } else { nodes[parentId - 1] -> right = nodes[childId - 1]; } } Node *rootNode = orphanNodes.begin() -> second; locateLeftmostNode(rootNode, 0, K); locateRightmostNode(rootNode, 0, K); input_stream.close(); return 0; }