递归函数后的新行

New line after a recursive function

我写了一个函数,它将在树的特定级别在单行中打印所有节点,现在我想在打印后换行 所有节点,我可以在主函数中轻松完成,但我想不出在函数本身中完成它的方法。我想在 main 函数之前的 printLevelK 函数中执行此操作,我包含了整个代码以防有人想要 运行 它:

#include <iostream>
#include <queue>
#include <vector>
using namespace std; 
// T is template parameter the typename keyword say that this parameter is a palceholder for type
template <typename T>
class treeNode{
    public:
    T data;
    vector<treeNode<T>*> childNodes; // vector for storing pointer to child treenode
    //Constructor for treeNode, it means it needs some data as argument for creating Tree node
    treeNode(T data){
        this->data = data;
    }
};

treeNode<int>* takeInput(){
    int rootdata;
    cout<<"Enter root data"<<endl;
    cin>>rootdata;
    treeNode<int>* root = new treeNode<int>(rootdata);
    queue<treeNode<int>*> pendingNodes;
    pendingNodes.push(root);
    while(pendingNodes.size()!=0){
        treeNode<int> *front=pendingNodes.front();
        cout<<"Enter number of child nodes of "<<front->data<<endl;
        int n;
        cin>>n;
        pendingNodes.pop();
        for(int i=1;i<=n;i++){
            cout<<"enter "<<i<<" child"<<endl;
            int childData;
            cin>>childData;
            treeNode<int>* child=new treeNode<int>(childData);
            (*front).childNodes.push_back(child);
            pendingNodes.push(child);
        }
    }
    return root;
}

int nodeNum(treeNode<int>* root){
    if(root== NULL)
        return 0;
    int res=1;
    for(int i=0;i<root->childNodes.size();i++){
        res+= nodeNum(root->childNodes[i]);
    }
return res;
}

void printLevelK(treeNode<int>* root, int k){
    if(root==NULL)
        return;
    if(k==0){
        cout<<root->data<<" ";
        return;
    }
    for(int i=0;i<root->childNodes.size(); i++){
        printLevelK(root->childNodes[i], k-1);
    }
//cout<<"\n"; this will add multiple newlines according to how many times 
            this function is called
}


int main(){
    treeNode<int>* root=takeInput();
    print(root);
    cout<<"Height of the tree: "<<maxHeight(root)<<endl;
    printLevelK(root,2);
    //cout<<"\n"; I could have break the line here
    cout<<"number of node is the tree: "<<nodeNum(root)<<endl;
    return 0;
}

是这样的吗?

void printLevelK(treeNode<int>* root, int k, bool newline=true){
    if(root==NULL)
        return;
    if(k==0){
        cout<<root->data<<" ";
        if (newline) { cout << "\n"; }
        return;
    }
    for(int i=0;i<root->childNodes.size(); i++){
        printLevelK(root->childNodes[i], k-1, false);
    }
    if (newline) { cout << "\n"; }
}