/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 * Definition of Doubly-ListNode
 * class DoublyListNode {
 * public:
 *     int val;
 *     DoublyListNode *next, *prev;
 *     DoublyListNode(int val) {
 *         this->val = val;
           this->prev = this->next = NULL;
 *     }
 * }
 */

class resultType{
public:
    DoublyListNode* head;
    DoublyListNode* tail;
    resultType() {
        this->head = NULL;
        this->tail = NULL;
    }
};

class Solution {
public:
    /**
     * @param root: The root of tree
     * @return: the head of doubly list node
     */
    DoublyListNode* bstToDoublyList(TreeNode* root) {
        // Write your code here
        return conversion(root).head;
    }

    resultType conversion(TreeNode* root) {
        resultType returnVal;
        if (root == NULL) {
            return returnVal;
        }

        resultType left = conversion(root->left);
        resultType right = conversion(root->right);

        DoublyListNode* mid = new DoublyListNode(root->val);
        if (left.tail != NULL) {
            left.tail->next = mid;
            mid->prev = left.tail;
        }
        if (right.head != NULL) {
            right.head->prev = mid;
            mid->next = right.head;
        }

        returnVal.head = left.head == NULL ? mid : left.head;
        returnVal.tail = right.tail == NULL ? mid : right.tail;

        return returnVal;
    }
};

results matching ""

    No results matching ""