-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProblem_4.java
More file actions
72 lines (54 loc) · 1.65 KB
/
Copy pathProblem_4.java
File metadata and controls
72 lines (54 loc) · 1.65 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
package trees.binarySearchTree;
// Problem Tiitle => Find inorder successor and inorder predecessor in a BST
public class Problem_4 {
// BST Node
static class Node {
int key;
Node left, right;
public Node() {
}
public Node(int key) {
this.key = key;
this.left = this.right = null;
}
}
static Node pre = new Node(), suc = new Node();
// This function finds predecessor and successor of key in BST.
// It sets pre and suc as predecessor and successor respectively
static void findPreSuc(Node root, int key) {
// Base case
if (root == null)
return;
// If key is present at root
if (root.key == key) {
// The maximum value in left subtree is predecessor
if (root.left != null) {
Node tmp = root.left;
while (tmp.right != null)
tmp = tmp.right;
pre = tmp;
}
// The minimum value in right subtree is successor
if (root.right != null) {
Node tmp = root.right;
while (tmp.left != null)
tmp = tmp.left;
suc = tmp;
}
return;
}
// If key is smaller than root's key, go to left subtree
if (root.key > key) {
suc = root;
findPreSuc(root.left, key);
}
// Go to right subtree
else {
pre = root;
findPreSuc(root.right, key);
}
}
// A utility function to insert a
public static void main(String[] args) {
}
}