« Create a tree and take input and print tree recursively

TreeNode.h

1#include <vector>
2using namespace std;
3
4template <typename T>
5class TreeNode
6{
7public:
8 T data;
9 vector<TreeNode<T> *> children;
10
11 TreeNode(T data)
12 {
13 this->data = data;
14 }
15
16 // current node won't be deleted before destructor is completed. So here we can do the cleanup
17 ~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_MIN
11#include <unordered_map>
12using namespace std;
13#include "TreeNode.h"
14#include <queue>
15
16
17TreeNode<int> *takeInput()
18{
19 int rootData;
20 cout << "Enter data" << endl;
21 cin >> rootData;
22 TreeNode<int> *root = new TreeNode<int>(rootData);
23
24 int n;
25 cout << "Enter num of children of " << rootData << endl;
26 cin >> n;
27
28 for (int i = 0; i < n; i++)
29 {
30 TreeNode<int> *child = takeInput();
31 root->children.push_back(child);
32 }
33 return root;
34}
35
36void printTree(TreeNode<int> *node)
37{
38 if (node == NULL)
39 {
40 return;
41 }
42 cout << node->data << " : ";
43 for (int i = 0; i < node->children.size(); i++)
44 {
45 cout << (node->children[i]->data) << ", ";
46 }
47 cout << endl;
48 for (int i = 0; i < node->children.size(); i++)
49 {
50 printTree(node->children[i]);
51 }
52}
53
54int main()
55{
56 TreeNode<int> *node = new TreeNode<int>(1);
57 TreeNode<int> *node1 = new TreeNode<int>(2);
58 TreeNode<int> *node2 = new TreeNode<int>(3);
59 node->children.push_back(node1);
60 node->children.push_back(node2);
61 printTree(node);
62 return 0;
63}