« Create a tree and take input and print tree recursively
TreeNode.h
1#include <vector>2using namespace std;34template <typename T>5class TreeNode6{7public:8 T data;9 vector<TreeNode<T> *> children;1011 TreeNode(T data)12 {13 this->data = data;14 }1516 // current node won't be deleted before destructor is completed. So here we can do the cleanup17 ~TreeNode()18 {19 for (int i = 0; i < children.size(); i++)20 {21 delete children[i];22 }23 }24};
TreeUse.cpp
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;13#include "TreeNode.h"14#include <queue>1516TreeNode<int> *takeInputLevelWise()17{18 int rootData;19 cout << "Enter root data: " << endl;20 cin >> rootData;21 TreeNode<int> *root = new TreeNode<int>(rootData);2223 queue<TreeNode<int> *> pendingNodes;2425 pendingNodes.push(root);26 while (!pendingNodes.empty())27 {28 TreeNode<int> *front = pendingNodes.front();29 pendingNodes.pop();30 cout << "Enter number of children of " << front->data << endl;31 int numChild;32 cin >> numChild;3334 for (int i = 0; i < numChild; i++)35 {36 int childData;37 cout << "Enter " << i << "th child of " << front->data << endl;38 cin >> childData;39 TreeNode<int> *child = new TreeNode<int>(childData);40 front->children.push_back(child);41 pendingNodes.push(child);42 }43 }44 return root;45}4647void printTree(TreeNode<int> *node)48{49 if (node == NULL)50 {51 return;52 }53 cout << node->data << " : ";54 for (int i = 0; i < node->children.size(); i++)55 {56 cout << (node->children[i]->data) << ", ";57 }58 cout << endl;59 for (int i = 0; i < node->children.size(); i++)60 {61 printTree(node->children[i]);62 }63}6465int main()66{67 TreeNode<int> *node = new TreeNode<int>(1);68 TreeNode<int> *node1 = new TreeNode<int>(2);69 TreeNode<int> *node2 = new TreeNode<int>(3);70 node->children.push_back(node1);71 node->children.push_back(node2);72 printTree(node);7374 TreeNode<int> *newRoot = takeInputLevelWise();75 printTree(newRoot);7677 delete newRoot;7879 return 0;80}