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 { constructor ( x ) { this . data = x ; this . left = null ; this . right = null ; } } let root ; let next = null ; function populateNext ( node ) { if ( node != null ) { populateNext ( node . right ) ; node . next = next ; next = node ; populateNext ( node . left ) ; } } root = new Node ( 10 ) root . left = new Node ( 8 ) root . right = new Node ( 12 ) root . left . left = new Node ( 3 ) p = populateNext ( root ) ptr = root . left . left while ( ptr != null ) { let print = ptr . next != null ? ptr . next . data : - 1 ; document . write ( " " + ptr . data + " " + print + " " ) ; ptr = ptr . next ; }