8000 Create print input tree level wise by nehatiwariii · Pull Request #343 · AllAlgorithms/cpp · GitHub
[go: up one dir, main page]

Skip to content

Create print input tree level wise #343

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Create print input tree level wise
  • Loading branch information
nehatiwariii authored Oct 14, 2021
commit 8bc9f20d006a9cead30e7060b761e2759ac8b7ba
82 changes: 82 additions & 0 deletions print input tree level wise
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

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];
}
}
};


TreeNode<int>* takeInputLevelWise() {
int rootData;
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();
pendingNodes.pop();
int numChild;
cin >> numChild;
for (int i = 0; i < numChild; i++) {
int childData;
cin >> childData;
TreeNode<int>* child = new TreeNode<int>(childData);
front->children.push_back(child);
pendingNodes.push(child);
}
}

return root;
}
#include<queue>
void printLevelWise(TreeNode<int>* root) {
queue<TreeNode<int>*>pendingnodes;
pendingnodes.push(root);
while(pendingnodes.size()!=0)
{
TreeNode<int>*Front=pendingnodes.front();
pendingnodes.pop();
cout<<Front->data<<":";
if(Front->children.size()==0)
cout<<endl;
else
{
for(int i=0;i<Front->children.size();i++)
{
if(i==Front->children.size()-1)
cout<<Front->children[i]->data<<endl;
else
{
cout<<Front->children[i]->data<<",";
}
TreeNode<int>* child= Front->children[i];
pendingnodes.push(child);

}
}

}


}


int main() {
TreeNode<int>* root = takeInputLevelWise();
printLevelWise(root);
}
0