Given a binary tree where each node has one extra pointer next, set it to the inorder successor for all binary tree nodes.

For example, consider the following tree. Here, the blue dotted line represents the next pointer for each node.

 
Set next pointer to inorder successor

The inorder successor of node 4 is 2
The inorder successor of node 2 is 1
The inorder successor of node 1 is 7
The inorder successor of node 7 is 5
The inorder successor of node 5 is 8
The inorder successor of node 8 is 3
The inorder successor of node 3 is 6
The inorder successor of node 6 is null

Practice this problem

The idea is to perform an inorder traversal of the tree and maintain the previously processed node for every tree node. Then set the next node to a previously visited node for every node in the inorder traversal. This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The inorder successor of 4 is 2
The inorder successor of 2 is 1
The inorder successor of 1 is 7
The inorder successor of 7 is 5
The inorder successor of 5 is 8
The inorder successor of 8 is 3
The inorder successor of 3 is 6

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(h) for call stack, where h is the height of the tree.