Skip to content

Commit e75e011

Browse files
Leaf node problem solved
1 parent 1e1bfa6 commit e75e011

3 files changed

+85
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"name":"Leaf Nodes","group":"HackerRank - Assignment 04 | Basic Data Structure | Batch 05","url":"https://www.hackerrank.com/contests/assignment-04-a-basic-data-structure-a-batch-05/challenges/leaf-nodes-1","interactive":false,"memoryLimit":512,"timeLimit":4000,"tests":[{"id":1724474168402,"input":"10 20 30 40 50 -1 60 -1 -1 -1 -1 -1 -1\n","output":"60 50 40\n"}],"testType":"single","input":{"type":"stdin"},"output":{"type":"stdout"},"languages":{"java":{"mainClass":"Main","taskClass":"LeafNodes"}},"batch":{"id":"b6171924-2d9e-4ee9-96fa-5203eb11ce02","size":1},"srcPath":"f:\\Tutorials\\Video Tutorials\\Phitron\\3. Basic Data Structures\\Leaf_Nodes.cpp"}

Leaf_Nodes.bin

129 KB
Binary file not shown.

Leaf_Nodes.cpp

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Node
5+
{
6+
public:
7+
int val;
8+
Node *left;
9+
Node *right;
10+
Node(int val)
11+
{
12+
this->val = val;
13+
this->left = NULL;
14+
this->right = NULL;
15+
}
16+
};
17+
18+
Node *input_binary_tree()
19+
{
20+
int val;
21+
cin >> val;
22+
Node *root;
23+
if (val == -1)
24+
root = NULL;
25+
else
26+
root = new Node(val);
27+
queue<Node *> q;
28+
if (root)
29+
q.push(root);
30+
31+
while (!q.empty())
32+
{
33+
Node *f = q.front();
34+
q.pop();
35+
36+
int l, r;
37+
cin >> l >> r;
38+
39+
Node *left, *right;
40+
if (l == -1)
41+
left = NULL;
42+
else
43+
left = new Node(l);
44+
45+
if (r == -1)
46+
right = NULL;
47+
else
48+
right = new Node(r);
49+
50+
f->left = left;
51+
f->right = right;
52+
53+
if (f->left)
54+
q.push(f->left);
55+
if (f->right)
56+
q.push(f->right);
57+
}
58+
return root;
59+
}
60+
61+
vector<int> v;
62+
63+
void leafNodeValues(Node *root)
64+
{
65+
if (root == NULL)
66+
return;
67+
if (root->left == NULL && root->right == NULL)
68+
v.push_back(root->val);
69+
leafNodeValues(root->left);
70+
leafNodeValues(root->right);
71+
}
72+
73+
int main()
74+
{
75+
Node *root = input_binary_tree();
76+
leafNodeValues(root);
77+
sort(v.begin(), v.end(), greater<int>());
78+
for (int i : v)
79+
{
80+
cout << i << " ";
81+
}
82+
83+
return 0;
84+
}

0 commit comments

Comments
 (0)