Flatten Tree to DLL **

// https://practice.geeksforgeeks.org/problems/leaves-to-dll/1#

bool help(Node* rootNode* &tmp){
    if(!root) return false;

    // if leaf: NODE SPECIFIC TECHNQIUE:
    if(!root->left and !root->right){
        tmp->right = root;
        root->left = tmp;
        
        tmp = root;
        return true;
    }    
    
    bool l = help(root->left, tmp);
    bool r = help(root->right, tmp);
    
    if(l) root->left = NULL;
    if(r) root->right = NULL;
    
    return false;
}

Node * convertToDLL(Node *root){
    // add code here.
    Node* dummy = new Node(-12);
    dummy->left = NULL;
    dummy->right = NULL;
    
    Node* tmp = dummy;
    help(root, tmp);
    tmp->right = NULL;
    
    Node* head = dummy->right;
    head->left = NULL;
    delete dummy;
    
    Node* prev = head;
    Node* cur = head->right;
    while(cur){
        cur->left = prev;
        prev = cur;
        cur = cur->right;
    }
    
    
    return head;

    
}

Comments

Popular Posts