eolymp
bolt
Try our new interface for solving problems
Problems

Tree Previous

Tree Previous

Binary search tree is given. Find element previous to the given in a tree.

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 function Prev that returns pointer to the previous element in a tree. If previous element does not exist, return NULL.

// Java
TreeNode Prev(TreeNode tree)
// C++
TreeNode* Prev(TreeNode *tree)

Example

prb10147.gif

Function Prev with tree pointing to 12 returns pointer to the node with value 9.

Time limit 1 second
Memory limit 128 MiB
Author Mykhailo Medvediev