Lexicographically smallest Palindromic Path in a Binary Tree

  
#include
using namespace std;
  

struct Node {
    char data;
    Node *left, *right;
};
  

Node* newNode(char data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
  

bool checkPalindrome(string s)
{
    int low = 0, high = (int)s.size() – 1;
  
    while (low < high) {            if (s[low] != s[high])             return false;            low++;         high--;     }        return true; }    void lexicographicallySmall(Node* root, string s,                             string& finalAns) {          if (root == NULL)         return;                  s += root->data;
  
    
    if (!root->left and !root->right) {
  
        if (checkPalindrome(s)) {
  
            
            
            if (finalAns == “$”)
                finalAns = s;
  
            
            
            else
                finalAns = min(finalAns, s);
        }
  
        return;
    }
  
    
    lexicographicallySmall(root->left,
                           s, finalAns);
  
    
    lexicographicallySmall(root->right,
                           s, finalAns);
}
  

void getPalindromePath(Node* root)
{
    
    
    string finalAns = “$”;
  
    
    
    
    lexicographicallySmall(root, “”,
                           finalAns);
  
    if (finalAns == “$”)
        cout left->left = newNode(‘a’);
    root->left->right = newNode(‘g’);
    root->right = newNode(‘b’);
    root->right->left = newNode(‘b’);
    root->right->right = newNode(‘x’);
    root->right->left->right = newNode(‘a’);
  
    getPalindromePath(root);
  
    return 0;
}