-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathNext larger.cpp
94 lines (74 loc) · 2.25 KB
/
Next larger.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
/*
Next larger
Given a generic tree and an integer n. Find and return the node with next larger element in the tree i.e. find a node with value just greater than n.
Note: Return NULL if no node is present with the value greater than n.
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.
The following line contains an integer, that denotes the value of n.
Output format :
The first and only line of output contains data of the node, whose data is just greater than n.
Constraints:
Time Limit: 1 sec
Sample Input 1 :
10 3 20 30 40 2 40 50 0 0 0 0
18
Sample Output 1 :
20
Sample Input 2 :
10 3 20 30 40 2 40 50 0 0 0 0
21
Sample Output 2:
30
*/
/************************************************************
Following is the structure for the TreeNode class
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];
}
}
};
************************************************************/
#include<queue>
#include<climits>
TreeNode<int>* getNextLargerElement(TreeNode<int>* root, int x) {
// Write your code here
//corner case
// If only root node is present
if(root -> children.size() == 0) {
if(root -> data > x) {
return root;
} else {
return NULL;
}
}
queue<TreeNode<int>*> q;
q.push(root);
TreeNode<int> *ans = root;
int diff = INT_MAX;
while(!q.empty()){
TreeNode<int> *front = q.front();
q.pop();
if(front -> data - x < diff and front -> data > x){
ans = front;
diff = front -> data - x;
}
for(int i = 0; i < front -> children.size(); i++){
q.push(front -> children[i]);
}
}
if(ans == root) {
return NULL;
} else {
return ans;
}
}