-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInOrderPredecessorInBST.java
45 lines (45 loc) · 1.24 KB
/
InOrderPredecessorInBST.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
/*
In Order predecessor in BST same as successor.
*/
public class InOrderPredecessorInBST {
public static void main(String[] args) {
TreeNode root=new TreeNode(50);
root.left=new TreeNode(20);
root.right=new TreeNode(100);
root.left.left=new TreeNode(10);
root.left.right=new TreeNode(30);
root.right.left=new TreeNode(80);
root.right.right=new TreeNode(110);
TreeNode ans=InOrderPredecessor(root,new TreeNode(110));
if (ans==null){
System.out.println(ans);
}
else {
System.out.println(ans.data);
}
}
public static TreeNode InOrderPredecessor(TreeNode root,TreeNode p){
if (root==null){
return null;
}
if (root.data>= p.data){
return InOrderPredecessor(root.left,p);
}
else {
TreeNode rightnode=InOrderPredecessor(root.right,p);
if (rightnode==null){
return root;
}else {
return rightnode;
}
}
}
}
class TreeNode{
int data;
TreeNode left,right;
public TreeNode(int key){
key=data;
left=right=null;
}
}