Skip to content

Commit d64893a

Browse files
committed
Inorder successor of BST
1 parent b7cc15d commit d64893a

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.interview.tree;
2+
3+
/**
4+
* Date 03/27/2016
5+
* @author Tushar Roy
6+
*
7+
* Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
8+
*
9+
* Time complexity O(h)
10+
* Space complexity O(h)
11+
*
12+
* https://leetcode.com/problems/inorder-successor-in-bst/
13+
*/
14+
public class InorderSuccessor {
15+
public Node inorderSuccessor(Node root, Node p) {
16+
if (p.right != null) {
17+
p = p.right;
18+
while (p.left != null) {
19+
p = p.left;
20+
}
21+
return p;
22+
} else {
23+
return succ(root, p.data);
24+
}
25+
}
26+
27+
private Node succ(Node root, int data) {
28+
if (root.data == data) {
29+
return null;
30+
}
31+
if (root.data < data) {
32+
return succ(root.right, data);
33+
} else {
34+
Node s = succ(root.left, data);
35+
return s == null ? root : s;
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)