Check if a Binary Tree consists of a pair of leaf nodes with sum K | Java program to implement the above approach ; 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 ; Driver Code ; Construct binary tree ; Stores the leaf nodes
import java . util . * ; class GFG { static boolean pairFound = false ; static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static void pairSum ( Node root , int target , HashSet < Integer > S ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { if ( S . contains ( target - root . data ) ) { System . out . print ( target - root . data + " ▁ " + root . data ) ; pairFound = true ; return ; } else S . add ( root . data ) ; } pairSum ( root . left , target , S ) ; pairSum ( root . right , target , S ) ; } public static void main ( String [ ] args ) { Node 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 ) ; HashSet < Integer > S = new HashSet < Integer > ( ) ; int K = 13 ; pairSum ( root , K , S ) ; if ( pairFound == false ) System . out . print ( " - 1" ) ; } }