Tree Previous#10147

Tree Previous

1 second
128 megabytes
Easy

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.

Definition of a tree

// 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)

Example

prb10147.gif

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.