Level Wise Print
/************************************************************
Following is the structure for the TreeNode class
template <typename T>
class TreeNode {
public:
T data;
vector<TreeNode<T>*> children;
TreeNode(T data) {
this->data = data;
}
~TreeNode() {
for (int i = 0; i < children.size(); i++) {
delete children[i];
}
}
};
************************************************************/
void printLevelWise(TreeNode<int>* root) {
// Write your code here
queue<TreeNode<int>*> pendingNode;//queue
pendingNode.push(root);
while(pendingNode.size()!=0){
TreeNode<int>* front=pendingNode.front();//front -> current root/ first ele of q
pendingNode.pop();
cout<<front->data<<":";
//int n;
// cin>>n;
for(int i=0;i<front->children.size();i++){
if (i==front->children.size()-1){
cout<<front->children[i]->data;
}
else{
cout<<front->children[i]->data<<",";
}
pendingNode.push(front->children[i]);
}
cout<<endl;
}
}
Comments
Post a Comment