Output the node that comes next to it at the same level. In case there is no such node output -1.The basic idea is that since for any given traversal we will always visit the given node before we visit it's neighbor, we can maintain some kind of a global or static variable that keeps track of the level of our node. Once we have that we can simply print the node that comes next at the same level during our traversal.

Now to keep track of the levels of various nodes we need to pass a variable showing the level we are currently in.

Here's the code for the problem:

We can use any traversal as long as the left subtree is explored before the right subtree. The code shown here uses inorder traversal. The main function called contains only the pointer to the node.So before we start our traversal we need to find the root. This can be done easily since we have the parent pointer for each node. We can use something like this to find root:

TreeNode* getRoot(node* ptr){ TreeNode* root=ptr; while(root->parent){ root=root->parent; } return root;}Here's the function that is called from our main, and along with it the utility function that does the actual computation for us.

The variable answer being returned in the original function can be declared globally. An important point to keep in mind here is that when we find our answer we need to set the flag to false again. If we don't do this the function will keep updating the answer and will ultimately store the rightmost node at that level.

Approach 2:

This is a slightly cleaner approach as it does not involve finding the root. Here's the algorithm:

Check for the base cases

if node is NULL then return NULL

if node -> parent is NULL then return NULL

if node is left child and parent has a right child too, then return node -> parent -> right.

Call the neighbour function for node's parent.

If the parent's neighbour doesn't have any child, find it's neighbour.

This will be repeated until we find a node that has a child, or the node has no neighbour

We can imagine this as applying level order traversal for the level of node's parent, recursively checking for all nodes in the penultimate level.