« Print tree level wise

Print Level Wise

Given a generic tree, print the input tree in level wise order.

For printing a node with data N, you need to follow the exact format -

N:x1,x2,x3,...,xn

where, N is data of any node present in the generic tree. x1, x2, x3, ...., xn are the children of node N.

You need to print all nodes in the level order form in different lines.

Input format :

The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.

Output Format :

The first and only line of output contains the elements of the tree in level wise order, as described in the task.

Constraints:

Time Limit: 1 sec

Sample Input 1:

10 3 20 30 40 2 40 50 0 0 0 0

Sample Output 1:

10:20,30,40

20:40,50

30:

40:

50:

1#include <iostream>
2#include <vector>
3#include <queue>
4using namespace std;
5
6template <typename T>
7class TreeNode {
8 public:
9 T data;
10 vector<TreeNode<T>*> children;
11
12 TreeNode(T data) { this->data = data; }
13
14 ~TreeNode() {
15 for (int i = 0; i < children.size(); i++) {
16 delete children[i];
17 }
18 }
19};
20
21void printLevelWise(TreeNode<int>* root) {
22 queue<TreeNode<int>*> pendingNodes;
23 pendingNodes.push(root);
24
25 while(!pendingNodes.empty()){
26 TreeNode<int>* top = pendingNodes.front();
27 pendingNodes.pop();
28 cout<<top->data<<":";
29 int len = top->children.size();
30 for(int i=0; i<len; i++){
31 TreeNode<int>* child = top->children[i];
32 cout<<child->data;
33 pendingNodes.push(child);
34 if(i != len - 1){
35 cout<<",";
36 }
37 }
38 cout<<endl;
39 }
40}
41
42TreeNode<int>* takeInputLevelWise() {
43 int rootData;
44 cin >> rootData;
45 TreeNode<int>* root = new TreeNode<int>(rootData);
46
47 queue<TreeNode<int>*> pendingNodes;
48
49 pendingNodes.push(root);
50 while (pendingNodes.size() != 0) {
51 TreeNode<int>* front = pendingNodes.front();
52 pendingNodes.pop();
53 int numChild;
54 cin >> numChild;
55 for (int i = 0; i < numChild; i++) {
56 int childData;
57 cin >> childData;
58 TreeNode<int>* child = new TreeNode<int>(childData);
59 front->children.push_back(child);
60 pendingNodes.push(child);
61 }
62 }
63
64 return root;
65}
66
67int main() {
68 TreeNode<int>* root = takeInputLevelWise();
69 printLevelWise(root);
70}