-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodes-at-depth k.cpp
94 lines (75 loc) · 1.76 KB
/
nodes-at-depth k.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//Program to print nodes at depth k in a generic tree
#include<bits/stdc++.h>
using namespace std;
// Following is the TreeNode structure
template <typename T>
class TreeNode
{
public:
T data;
vector<TreeNode<T>* > children;
TreeNode(T data)
{
this -> data = data;
}
~TreeNode()
{
for (int i = 0 ; i < children.size() ; i++)
{
delete children[i];
}
}
};
//Following is the function to print the nodes at depth k
void printNodesAtDepthK(TreeNode<int> *root , int k)
{
if(k == 0)
{
cout << root -> data << " ";
return;
}
for(int i = 0 ; i < root -> children.size() ; i++)
{
TreeNode<int> *t = root -> children[i];
printNodesAtDepthK(t , k - 1);
}
}
//Taking input level wise
TreeNode<int> * takeInputLevelWise()
{
int rootData;
cin >> rootData;
TreeNode<int> *root = new TreeNode<int>(rootData);
queue<TreeNode<int>* > pendingNodes;
pendingNodes.push(root);
while (pendingNodes.size() ! = 0)
{
int numChild;
TreeNode<int>* front = pendingNodes.front();
pendingNodes.pop();
cin >> numChild;
for (int i = 0 ; i < numChild ; i++)
{
int childData;
cin >> childData;
TreeNode<int> *child = new TreeNode<int>(childData);
front -> children.push_back(child);
pendingNodes.push(child);
}
}
return root;
}
int main()
{
TreeNode<int> *root = takeInputLevelWise();
int k;
cin >> k;
printNodesAtDepthK(root , k);
}
/***
Sample input:
10 3 20 30 40 2 40 50 0 0 0 0
1
Output:
20 30 40
****/