Monday, March 16, 2020

Convert Binary Search Tree to Sorted Doubly Linked List

class Solution { public: Node* treeToDoublyList(Node* root) { if (root == NULL) { return NULL; } Node *head = NULL, *tail = NULL; helper(root, head, tail); head -> left = tail; tail -> right = head; return head; } void helper(Node *& root, Node *& head, Node *& tail) { if (root == NULL) { return; } Node *left_tail = NULL; helper(root -> left, head, left_tail); if (left_tail != NULL) { left_tail -> right = root; root -> left = left_tail; } else { head = root; left_tail = root; } Node *right_head = NULL; helper(root -> right, right_head, tail); if (right_head != NULL) { root -> right = right_head; right_head -> left = root; } else { root -> right = NULL; tail = root; } return; } };

No comments:

Post a Comment