This was asked to me in an interview which I screwed up. We are given a binary tree , however , it is modified such that it's children are never null , if a non leaf node doesn't have a child then its right/left child points to the node itself. And for the leaf nodes , they point to the next left node and right node. For leftmost and rightmost node it will be pointing to itself and the previous/next element.
Example :
1
/ \
2 3
/ \ / \
(4 = 5 = 6 = 7)
Here 4.left = 4 , 4.right = 5 , 5.left = 4 and 5.right = 6 and so on.
We need to do an inorder traversal of this tree.
I came up with the conditions which will determine if a node is leaf node (exit condition):
if(root.right==root || root.left == root || root.left.right == root || root.right.left == root)
But couldn't combine these properly. Also we need to take care of skewed trees for which even the root satifies the condition root.left = root || root.right = right , so we will straight away get out of recursion without even traversing the whole tree.
Please help me with it. I couldn't come up with proper condition check for recursion.
We just need to do an in order traversal of this tree. Output : 4 2 5 1 6 3 7