-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevel_Nodes.cpp
More file actions
116 lines (102 loc) · 1.99 KB
/
Level_Nodes.cpp
File metadata and controls
116 lines (102 loc) · 1.99 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *left;
Node *right;
Node(int val)
{
this->val = val;
this->left = NULL;
this->right = NULL;
}
};
Node *input_binary_tree()
{
int val;
cin >> val;
Node *root;
if (val == -1)
root = NULL;
else
root = new Node(val);
queue<Node *> q;
if (root)
q.push(root);
while (!q.empty())
{
Node *f = q.front();
q.pop();
int l, r;
cin >> l >> r;
Node *left, *right;
if (l == -1)
left = NULL;
else
left = new Node(l);
if (r == -1)
right = NULL;
else
right = new Node(r);
f->left = left;
f->right = right;
if (f->left)
q.push(f->left);
if (f->right)
q.push(f->right);
}
return root;
}
int maxHeight(Node *root)
{
if (!root)
return 0;
int l = maxHeight(root->left);
int r = maxHeight(root->right);
return max(l, r) + 1;
}
void printLevelNodes(Node *root, int x)
{
if (!root)
return;
int depth = maxHeight(root);
if (x == 0)
{
cout << root->val << endl;
}
else if (x > depth - 1)
{
cout << "Invalid" << endl;
}
else
{
queue<pair<Node *, int>> q;
q.push({root, 0});
while (!q.empty())
{
pair<Node *, int> f = q.front();
q.pop();
Node *node = f.first;
int level = f.second;
// Ja kaj korar korbo
if (level == x)
{
cout << node->val << " ";
}
if (node->left)
q.push({node->left, level + 1});
if (node->right)
q.push({node->right, level + 1});
}
}
}
int main()
{
Node *root = input_binary_tree();
int x;
cin >> x;
printLevelNodes(root, x);
return 0;
}