# How to print a level of a binary search tree?

If we have say, a tree with a depth of 2:

``````          6        <- depth = 0
/ \
/   \
4     9     <- depth = 1
/ \     \
3   5     10  <- depth = 2
``````

And I only want to print the second level, so 3, 5, and 10 (in that order), how would I go about doing this? I’m using the code I wrote for my inorder traversal but I’m stuck on how to track depth of the tree and print when I’m at said depth.

``````void printLevelNodesHelper(MovieNode * curr, int level){ //helper function
int lvl = level; //store initial value of level
if(curr != NULL){
printLevelNodesHelper(curr->left, level+1);
if(level == lvl){
cout << "Movie: " << curr->title << " " << curr->rating << endl;
}
printLevelNodesHelper(curr->right, level+1);
}
}

void MovieTree::printLevelNodes(int k){ //k is the desired level
MovieNode * curr = root;
if(root == NULL){ //if the tree is empty exit it
return;
}
else if(k == 0){ //print the root's title
cout << "Movie: " << curr->title << " " << curr->rating << endl;
}
else{
printLevelNodesHelper(curr, k);
}
}
``````

Here’s the info for my struct and class

``````struct MovieNode{
int ranking;
string title;
int year;
float rating;

MovieNode* left = NULL;
MovieNode* right = NULL;

};

class MovieTree{
private:
MovieNode* root;

public:
MovieTree();
~MovieTree();
void printMovieInventory();
void addMovieNode(int ranking, std::string title, int year, float rating);
void findMovie(std::string title);
void queryMovies(float rating, int year);
void averageRating();
void printLevelNodes(int k);
};
``````