Populate Inorder Successor for all nodes | A binary tree node ; Set next of p and all descendants of p by traversing them in reverse Inorder ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; First set the next pointer in right subtree ; Set the next as previously visited node in reverse Inorder ; Change the prev for subsequent node ; Finally , set the next pointer in left subtree ; Constructed binary tree is 10 / \ 8 12 / 3 ; Populates nextRight pointer in all nodes ; Let us see the populated values ; - 1 is printed if there is no successor
class Node { int data ; Node left , right , next ; Node ( int item ) { data = item ; left = right = next = null ; } } class BinaryTree { Node root ; static Node next = null ; void populateNext ( Node node ) { if ( node != null ) { populateNext ( node . right ) ; node . next = next ; next = node ; populateNext ( node . left ) ; } } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 10 ) ; tree . root . left = new Node ( 8 ) ; tree . root . right = new Node ( 12 ) ; tree . root . left . left = new Node ( 3 ) ; tree . populateNext ( tree . root ) ; Node ptr = tree . root . left . left ; while ( ptr != null ) { int print = ptr . next != null ? ptr . next . data : - 1 ; System . out . println ( " Next ▁ of ▁ " + ptr . data + " ▁ is : ▁ " + print ) ; ptr = ptr . next ; } } }