Check if a Binary Tree consists of a pair of leaf nodes with sum K | Stores if a pair exists or not ; Struct binary tree node ; Creates a new node ; Function to check if a pair of leaf nodes exists with sum K ; Checks if root is null ; Checks if the current node is a leaf node ; Checks for a valid pair of leaf nodes ; Insert value of current node into the set ; Traverse left and right subtree ; Construct binary tree ; Stores the leaf nodes
let pairFound = false ; class Node { constructor ( data ) { this . left = null ; this . right = null ; this . data = data ; } } function newNode ( data ) { let temp = new Node ( data ) ; return temp ; } function pairSum ( root , target , S ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { if ( S . has ( target - root . data ) ) { document . write ( target - root . data + " " + root . data ) ; pairFound = true ; return ; } else S . add ( root . data ) ; } pairSum ( root . left , target , S ) ; pairSum ( root . right , target , S ) ; } let root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; root . right = newNode ( 3 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 7 ) ; root . right . right . right = newNode ( 8 ) ; let S = new Set ( ) ; let K = 13 ; pairSum ( root , K , S ) ; if ( pairFound == false ) document . write ( " " ) ;