-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
inorderSuccessorInBST.java
65 lines (59 loc) · 1.57 KB
/
inorderSuccessorInBST.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Source : http://www.lintcode.com/en/problem/inorder-successor-in-bst/
// https://leetcode.com/problems/inorder-successor-in-bst/
// Inspired by : http://www.jiuzhang.com/solutions/inorder-successor-in-bst/
// Author : Lei Cao
// Date : 2015-10-06
/**********************************************************************************
*
* Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
*
* Example
* Given tree = [2,1] and node = 1:
*
* 2
* /
* 1
* return node 2.
*
* Given tree = [2,1,3] and node = 2:
*
* 2
* / \
* 1 3
*
* return node 3.
*
* Note
* If the given node has no in-order successor in the tree, return null.
*
* Challenge
* O(h), where h is the height of the BST.
**********************************************************************************/
package inorderSuccessorInBST;
public class inorderSuccessorInBST {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode successor = null;
if (root == null) {
return null;
}
while (root != null && root.val != p.val) {
if (root.val > p.val) {
successor = root;
root = root.left;
} else {
root = root.right;
}
}
if (root == null) {
return null;
}
if (root.right == null) {
return successor;
}
root = root.right;
while (root.left != null) {
root = root.left;
}
return root;
}
}