Given a binary search tree and a reference to a node, find the previous element in in-order traversal (that is, the in-order predecessor) of the given node.
// Java
class TreeNode
{
public:
int val;
TreeNode left, right, parent;
TreeNode(int x, TreeNode prev) {
val = x;
left = NULL;
right = NULL;
parent = prev;
}
};// C++
class TreeNode
{
public:
int val;
TreeNode *left, *right, *parent;
TreeNode(int x, TreeNode *prev = NULL) : val(x), left(NULL), right(NULL), parent(prev) {}
};Implement the function Prev, which returns a pointer to the previous element in the binary search tree (the in-order predecessor of the given node). If the previous element does not exist, return NULL.
// Java
TreeNode Prev(TreeNode tree)// C++
TreeNode* Prev(TreeNode *tree)
If the function Prev is called with tree pointing to the node with value 12, the function returns a pointer to the node with value 9.