The tree is given by the list of arcs. The first array is the beginning of the arc, the second array is the end of the arc.

A(2, 2, 3, 3, 5, 5, 6, 9, 1) B(3, 5, 6, 9, 4, 1, 10, 15, 22) 

How to find the k-th level of the tree? Root = 2 is zero. S. language

  • @Dread, According to the rules of the forum, questions should not be limited to the decision or the completion of student assignments. Please clarify what you have done yourself and what did not work out. - Nicolas Chabanovsky
  • one
    A person may want to know the algorithm - Dzhioev

1 answer 1

You can use the search in width, with a stop after the level we need. I will write the code in C ++, the algorithm itself will be clear:

 vector<int> findLevel(Node* root, int targetLevel) { queue<pair<Node*, int>> Q; Q.push(make_pair(root, 0)); vector<int> result; while (!Q.empty()) { Node* curNode = Q.top().first; int curLevel = Q.top().second; Q.pop(); if (curLevel > targetLevel) { break; } if (curLevel == targetLevel) { result.push_back(curNode->value); } for (int i = 0; i < curNode->childrenNumber(); ++i) { Q.push(make_pair(curNode->child(i), curLevel + 1)); } } return result; }