« Print all nodes at level K

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 <queue>
14
15template <typename T>
16class TreeNode
17{
18public:
19 T data;
20 vector<TreeNode<T> *> children;
21
22 TreeNode(T data)
23 {
24 this->data = data;
25 }
26
27 // current node won't be deleted before destructor is completed. So here we can do the cleanup
28 ~TreeNode()
29 {
30 for (int i = 0; i < children.size(); i++)
31 {
32 delete children[i];
33 }
34 }
35};
36
37void printAtLevelK(TreeNode<int> *node, int level)
38{
39 if (level == 0)
40 {
41 cout << node->data << endl;
42 return;
43 }
44
45 for (int i = 0; i < node->children.size(); i++)
46 {
47 printAtLevelK(node->children[i], level - 1);
48 }
49}
50
51int main()
52{
53 TreeNode<int> *node = new TreeNode<int>(1);
54 TreeNode<int> *node1 = new TreeNode<int>(2);
55 TreeNode<int> *node2 = new TreeNode<int>(3);
56 node->children.push_back(node1);
57 node->children.push_back(node2);
58 printTree(node);
59
60 // TreeNode<int> *newRoot = takeInput();
61 // printTree(newRoot);
62
63 TreeNode<int> *newRoot = takeInputLevelWise();
64 printTree(newRoot);
65
66 int ans = numNodes(newRoot);
67 cout << "NUM NODES:" << ans << endl;
68
69 cout << "---------PREORDER---------" << endl;
70 preOrder(newRoot);
71 cout << endl;
72 cout << "---------PREORDER---------" << endl;
73
74 // This is one way
75 // deleteTree(newRoot);
76
77 // another way here is to use destructors
78 delete newRoot;
79
80 return 0;
81}