Given a Binary Tree, complete the function to populate the next pointer for all nodes. The next pointer for every node should point to the Inorder successor of the node.
Note: The node having no in-order successor will be pointed to -1.
Output: 3->8 8->10 10->12 12->-1 Explanation: The inorder of the above tree is : 3 8 10 12. So the next pointer of node 3 is pointing to 8 , next pointer of 8 is pointing to 10 and so on and next pointer of 12 is pointing to -1 as there is no inorder successor of 12.
Output: 3->2 2->1 1->-1 Explanation: The inorder of the above tree is: 3 2 1. So the next pointer of node 3 is pointing to 2 , next pointer of 2 is pointing to 1. And next pointer of 1 is pointing to -1 as there is no inorder successor of 1..
[Naive Approach] Storing Inorder - O(n) Time and O(n)
The intuition is to perform an inorder traversal of the binary tree because inorder naturally gives nodes in the order of their successors
Do Inorder traversal and store it in an array.
Traverse the array and connect every node with next to it in the array.
Output
3->8 8->10 10->12 12->-1
[Expected Approach] Reverse Inorder - O(n) Time and O(1) Space
Traverse the given tree in reverse inorder traversal and keep track of previously visited node. When a node is being visited, assign a previously visited node as next.