VOOZH about

URL: https://www.geeksforgeeks.org/dsa/populate-inorder-successor-for-all-nodes/

⇱ Populate Inorder Successor for all nodes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Populate Inorder Successor for all nodes

Last Updated : 26 Apr, 2026

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.

Example:

Input:

👁 2056957815
Binary Tree

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.

Input:

👁 2056957816

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.


Output
3->8 8->10 10->12 12->-1
Comment
Article Tags:
Article Tags: