-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPredecessor And Successor Of An Element
101 lines (82 loc) · 2.16 KB
/
Predecessor And Successor Of An Element
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
import java.io.*;
import java.util.*;
public class Main {
private static class Node {
int data;
ArrayList< Node> children = new ArrayList< >();
}
public static void display(Node node) {
String str = node.data + " -> ";
for (Node child : node.children) {
str += child.data + ", ";
}
str += ".";
System.out.println(str);
for (Node child : node.children) {
display(child);
}
}
public static Node construct(int[] arr) {
Node root = null;
Stack< Node> st = new Stack< >();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1) {
st.pop();
} else {
Node t = new Node();
t.data = arr[i];
if (st.size() > 0) {
st.peek().children.add(t);
} else {
root = t;
}
st.push(t);
}
}
return root;
}
static Node predecessor;
static Node successor;
static int state;
public static void predecessorAndSuccessor(Node node, int data) {
// write code here
if(state==0){
if(node.data==data){
state = 1;
}else{
predecessor = node;
}
}else if(state==1){
state = 2;
successor = node;
}
for(Node child : node.children){
predecessorAndSuccessor(child,data);
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(values[i]);
}
int data = Integer.parseInt(br.readLine());
Node root = construct(arr);
predecessor = null;
successor = null;
state = 0;
predecessorAndSuccessor(root, data);
if (predecessor == null) {
System.out.println("Predecessor = Not found");
} else {
System.out.println("Predecessor = " + predecessor.data);
}
if (successor == null) {
System.out.println("Successor = Not found");
} else {
System.out.println("Successor = " + successor.data);
}
}
}