-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path30 tree_Leaf node.cpp
More file actions
115 lines (100 loc) · 1.78 KB
/
30 tree_Leaf node.cpp
File metadata and controls
115 lines (100 loc) · 1.78 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
/*
Given a binary search tree with N nodes, implement a function print_leaf(node* root) to print all the leaf nodes in descending order.
Input Format
First line reads the number of nodes and second line reads the elements of the tree.
Example:
5
10 5 20 30 15
Constraints
N > 0
Output Format
Prints all the nodes of BST in descending order
Example:
30 15 5
Sample Input 0
5
10 5 20 30 15
Sample Output 0
30 15 5
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct node
{
int data;
node *left=NULL;
node *right=NULL;
};
node *root=NULL,*loc=NULL,*locp=NULL;
void find(int x)
{
node *cur=root;
node *curp=NULL;
while(cur!=NULL)
{
if(cur->data==x)
{
loc = cur;
break;
}
else if(cur->data>x)
{
curp = cur;
cur=cur->left;
}
else
{
curp = cur;
cur=cur->right;
}
}
if(cur==NULL)
{
loc =cur;
locp=curp;
}
}
void insert(int x)
{
find(x);
if(loc==NULL)
{
node *NEW =new node;
NEW->data=x;
if(locp==NULL)
root=NEW;
else if(x<locp->data)
locp->left=NEW;
else
locp->right=NEW;
}
}
void leaf_node(node *head)
{
if(head==NULL)
return;
leaf_node(head->right);
if(head->left==NULL&&head->right==NULL)
{
cout<<head->data<<" ";
return;
}
leaf_node(head->left);
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
insert(x);
}
leaf_node(root);
return 0;
}