Check if a Binary Tree consists of a pair of leaf nodes with sum K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool pairFound = false ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void pairSum ( Node * root , int target , unordered_set < int > & S ) { if ( ! root ) return ; if ( ! root -> left and ! root -> right ) { if ( S . count ( target - root -> data ) ) { cout << target - root -> data << " ▁ " << root -> data ; pairFound = true ; return ; } else S . insert ( root -> data ) ; } pairSum ( root -> left , target , S ) ; pairSum ( root -> right , target , S ) ; } int main ( ) { 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 ) ; unordered_set < int > S ; int K = 13 ; pairSum ( root , K , S ) ; if ( pairFound == false ) cout << " - 1" ; return 0 ; }