eolymp
bolt
Try our new interface for solving problems
Problems

Tree Next

Tree Next

Binary search tree is given. Find element next 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 Next that returns pointer to the next element in a tree. If next element does not exist, return NULL.

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

Example

prb10146.gif

Function Next with tree pointing to 8 returns pointer to the node with value 9.

Time limit 1 second
Memory limit 128 MiB
Author Mykhailo Medvediev