« 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_MIN11#include <unordered_map>12using namespace std;13#include <queue>1415template <typename T>16class TreeNode17{18public:19 T data;20 vector<TreeNode<T> *> children;2122 TreeNode(T data)23 {24 this->data = data;25 }2627 // current node won't be deleted before destructor is completed. So here we can do the cleanup28 ~TreeNode()29 {30 for (int i = 0; i < children.size(); i++)31 {32 delete children[i];33 }34 }35};3637void printAtLevelK(TreeNode<int> *node, int level)38{39 if (level == 0)40 {41 cout << node->data << endl;42 return;43 }4445 for (int i = 0; i < node->children.size(); i++)46 {47 printAtLevelK(node->children[i], level - 1);48 }49}5051int 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);5960 // TreeNode<int> *newRoot = takeInput();61 // printTree(newRoot);6263 TreeNode<int> *newRoot = takeInputLevelWise();64 printTree(newRoot);6566 int ans = numNodes(newRoot);67 cout << "NUM NODES:" << ans << endl;6869 cout << "---------PREORDER---------" << endl;70 preOrder(newRoot);71 cout << endl;72 cout << "---------PREORDER---------" << endl;7374 // This is one way75 // deleteTree(newRoot);7677 // another way here is to use destructors78 delete newRoot;7980 return 0;81}