Tree goodbye
#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;
}
};
void printTree(TreeNode<int>* root){
cout<<root->data<<":";
for (int i=0;i<root->children.size();i++){
cout<<root->children[i]->data<<",";
}
cout<<endl;
for (int i=0;i<root->children.size();i++){
printTree(root->children[i]);
}
}
TreeNode<int>* takeInput(){
int rootData;
cout<<"Enter Data: ";
cin>>rootData;
TreeNode <int>* root = new TreeNode<int>(rootData);
cout<<"Enter number of children of "<<rootData<<": ";
int n;
cin>>n;
for(int i=0;i<n;i++){
TreeNode<int>*child=takeInput();
root->children.push_back(child);
}
return root;
}
TreeNode<int>* takeInputLevel(){
int rootData;
cout<<"Enter Data: "<<endl;
cin>>rootData;
TreeNode <int>* root = new TreeNode<int>(rootData);
queue<TreeNode<int>*> pendingNode;//queue
pendingNode.push(root);
while(pendingNode.size()!=0){
TreeNode<int>*front = pendingNode.front();
pendingNode.pop();
cout<<"Enter the number of children of "<<front->data<<endl;
int childnum;
cin>>childnum;
for (int i=0;i<childnum;i++){
cout<<"Enter the "<<i<<"th data of root"<<front->data<<endl;
int childata;
cin>>childata;
TreeNode <int>* child = new TreeNode<int>(childata);
pendingNode.push(child);
front->children.push_back(child);
}
}
return root;
}
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;
}
}
int numNodes(TreeNode<int>* root){
int ans=1;
for(int i=0;i<root->children.size();i++){
ans+=numNodes(root->children[i]);
}
return ans;
}
void printAtLevel(TreeNode<int>* root, int k){
if (root==NULL){
return;
}
if (k==0){
cout<<root->data<<" ";
return;
}
for (int i=0;i<root->children.size();i++){
printAtLevel(root->children[i],k-1);
}
}
void preorder(TreeNode<int>* root){
if(root==NULL){
return;
}
for(int i=0;i<root->children.size();i++){
preorder(root->children[i]);
}
cout<<root->data<<" ";
}
int main(){
// TreeNode<int>* root=new TreeNode<int>(1);
// TreeNode<int>* node1=new TreeNode<int>(2);
// TreeNode<int>* node2=new TreeNode<int>(3);
// root->children.push_back(node1);
// root->children.push_back(node2);
TreeNode<int>*root=takeInputLevel();
preorder(root);
cout<<endl;
printLevelWise(root);
cout<<endl;
cout<<"At level 2 ";
printAtLevel(root,2);
cout<<endl;
cout<<numNodes(root);
}
Comments
Post a Comment