-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProblem_17.java
More file actions
64 lines (54 loc) · 1.84 KB
/
Copy pathProblem_17.java
File metadata and controls
64 lines (54 loc) · 1.84 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
// Replace every element with the least greater element on its right
class Problem_17 {
// A binary tree node
static class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
Node root;
// Function to insert a new node with given key in BST
static Node insert(Node node, int key, Wrapper succ) {
// If the tree is empty, return a new node
if (node == null) {
return new Node(key);
}
// If key is smaller than node's key, go to left subtree
if (key < node.data) {
succ.node = node; // Update successor
node.left = insert(node.left, key, succ);
}
// If key is greater than or equal to node's key, go to right subtree
else {
node.right = insert(node.right, key, succ);
}
return node;
}
// Wrapper class to hold successor node
static class Wrapper {
Node node;
}
// Function to replace every element with the least greater element on its right
static void replaceWithLeastGreater(int[] arr) {
Node root = null;
// Traverse the array from right to left
for (int i = arr.length - 1; i >= 0; i--) {
Wrapper succ = new Wrapper();
root = insert(root, arr[i], succ);
// Replace arr[i] with its successor if it exists
arr[i] = (succ.node != null) ? succ.node.data : -1;
}
}
// Driver method to test above methods
public static void main(String args[]) {
int[] arr = {8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28};
replaceWithLeastGreater(arr);
System.out.println("Modified array:");
for (int value : arr) {
System.out.print(value + " ");
}
}
}