forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInorderSuccessorInBST.java
70 lines (64 loc) · 2.19 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
66
67
68
69
70
package tree;
/**
* Created by gouthamvidyapradhan on 14/05/2017.
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.
Solution: The below solution works with worst case time complexity of O(h) where h is the height of the tree.
If the current node is <= target_node, recursively iterate the right of the current node.
else if the current node is > target_node then mark the current node as the successor and recursively iterate the left of the current node.
*/
public class InorderSuccessorInBST
{
public static class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/**
* Main method
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(6);
root.right = new TreeNode(15);
root.right.left = new TreeNode(13);
root.right.left.left = new TreeNode(12);
root.right.left.right = new TreeNode(14);
root.right.right = new TreeNode(17);
TreeNode ans = new InorderSuccessorInBST().inorderSuccessor(root, root.right.left.right);
if(ans != null)
System.out.println(ans.val);
else System.out.println(ans);
}
/**
* Find successor
* @param root root node
* @param p target
* @return successor
*/
public TreeNode inorderSuccessor(TreeNode root, TreeNode p)
{
return inOrder(root, p, null);
}
/**
* Inorder traversal
* @param curr current node
* @param target target node
* @param successor successor
* @return successor node
*/
private TreeNode inOrder(TreeNode curr, TreeNode target, TreeNode successor)
{
if(curr == null) return successor;
if(curr.val <= target.val)
return inOrder(curr.right, target, successor);
return inOrder(curr.left, target, curr); //make the current node as successor
}
}