public class InorderSuccessorInBST { // a balanced binary tree to find successor node public the TreeNode inorderSuccessor (the TreeNode the root, the TreeNode P) { IF (P == null ) { return null ; } IF (getLastEntry (the root) == P) { // root the rightmost node is the last node, there is no successor node. return null ; } IF (! p.right = null ) { // find the first node left and right most node. return getFirstEntry (p.right); } // p.right == null the TreeNode the root = parent; //Only left, right no parent node. TEMP = the TreeNode the root; the while (parent =! Null ) { IF (parent == P) { BREAK ; } the else IF (p.val <parent.val) { // take the left when, twmp pointing to a parent node, parent point child nodes. Next to go. = TEMP parent; parent = parent.left; } the else { // the right time to go, temp unchanged, parent = parent.right; } } return TEMP; } private TreeNode getLastEntry(TreeNode p) { while (p.right != null) { p = p.right; } return p; } private TreeNode getFirstEntry(TreeNode p) { while (p.left != null) { p = p.left; } return p; } }