|
| 1 | +/* |
| 2 | +Given the root of a binary search tree and a node p in it, return the in-order successor of that node in the BST. If the |
| 3 | +given node has no in-order successor in the tree, return null. |
| 4 | +The successor of a node p is the node with the smallest key greater than p.val. |
| 5 | +
|
| 6 | +Example 1: |
| 7 | +Input: root = [2,1,3], p = 1 |
| 8 | +Output: 2 |
| 9 | +Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type. |
| 10 | +
|
| 11 | +Algorithm |
| 12 | +
|
| 13 | +If the value of the root node is less than or equal to the value of the p node, it means that the successor |
| 14 | +node of p must be in the right subtree, so this function is recursively called on the right child node. |
| 15 | +If the value of the root node is greater than the value of p, then it is possible that the root node is the |
| 16 | +successor of p, or a node in the left subtree is a successor of p, * So first call this function recursively |
| 17 | +on the left child node, * If it returns empty, indicating that the root node is a successor node, just return, |
| 18 | +* If it is not empty, return that node |
| 19 | +
|
| 20 | + */ |
| 21 | + |
| 22 | +public class InOrderSuccessorInBST { |
| 23 | + public static void main(String[] args) { |
| 24 | + TreeNode root=new TreeNode(50); |
| 25 | + root.left=new TreeNode(20); |
| 26 | + root.right=new TreeNode(100); |
| 27 | + root.left.left=new TreeNode(10); |
| 28 | + root.left.right=new TreeNode(30); |
| 29 | + root.right.left=new TreeNode(80); |
| 30 | + root.right.right=new TreeNode(110); |
| 31 | + TreeNode ans=InOrderSuccessor(root,new TreeNode(110)); |
| 32 | + if (ans==null){ |
| 33 | + System.out.println(ans); |
| 34 | + } |
| 35 | + else { |
| 36 | + System.out.println(ans.data); |
| 37 | + } |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + } |
| 42 | + public static TreeNode InOrderSuccessor(TreeNode root,TreeNode p){ |
| 43 | + if (root==null){ |
| 44 | + return null; |
| 45 | + } |
| 46 | + if (root.data<= p.data){ |
| 47 | + return InOrderSuccessor(root.right,p); |
| 48 | + } |
| 49 | + else { |
| 50 | + TreeNode leftnode=InOrderSuccessor(root.left,p); |
| 51 | + if (leftnode == null) { |
| 52 | + return root; |
| 53 | + } else { |
| 54 | + return leftnode; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +class TreeNode{ |
| 60 | + int data; |
| 61 | + TreeNode left,right; |
| 62 | + public TreeNode(int key){ |
| 63 | + key=data; |
| 64 | + left=right=null; |
| 65 | + } |
| 66 | +} |
0 commit comments