Pre-order Successor of a Node

Question

A binary search tree is a full binary tree in which every internal node holds a number. Moreover, any number in a node $x$ is larger than any number in the left subtree of $x$ and smaller than any number in its right subtree. Any leaf contains no data and holds a special symbol nil. An example is given below.

Any node x has 4 fields, $key(x), father(x), left(x),$ and $right(x)$, where $key(x)$ is the value of the number stored in $x$. The other three are pointers to its father node, left child and right child, respectively. The father of the root is nil. Obviously, if we do pre-order, we will get a sorted (not including leaves). A node $y$ is called the successor of $x$ if $key(y)$ is the next number after $key(x)$ in the sorted sequence. For example, in the following example, 13 is the successor of 10. Please write a program or a pseudo code that finds the successor for a given node $x$.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Get-Successor(T, root, x)
    if (left(x) != nil)         # case 1: node has left child
              return left(x)

    else         # case 2: No left or right child. Then we travel up.
              while (father(x) != nil & right(father(x)) == x) 
                      x  father(x)
                    father(x)  father(parent(x))
    if (father(x) = nil)        # we reach the root. No result found
                return nil

    return right(father(x)) 
End