-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindtheInorderPredecessor.java
48 lines (42 loc) · 1.25 KB
/
FindtheInorderPredecessor.java
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
/*************************************************************
Following is the Binary Tree node structure
class TreeNode<T> {
public T data;
public TreeNode<T> left;
public TreeNode<T> right;
TreeNode(T data) {
this.data = data;
left = null;
right = null;
}
}
*************************************************************/
import java.util.ArrayList;
public class Solution {
public static ArrayList<Integer> predecessorSuccessor(BinaryTreeNode<Integer> root, int key) {
int successor = -1;
int predecessor = -1;
BinaryTreeNode<Integer> troot = root;
while(troot!=null){
if(key>=troot.data)
troot = troot.right;
else{
successor = troot.data;
troot = troot.left;
}
}
troot = root;
while(troot!=null){
if(key<=troot.data)
troot = troot.left;
else{
predecessor = troot.data;
troot = troot.right;
}
}
ArrayList<Integer> list = new ArrayList<>();
list.add(predecessor);
list.add(successor);
return list;
}
}