Skip to content

Latest commit

 

History

History
 
 

426. Convert Binary Search Tree to Sorted Doubly Linked List

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.

You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.

We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.

 

Example 1:

Input: root = [4,2,5,1,3]


Output: [1,2,3,4,5]

Explanation: The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.

Example 2:

Input: root = [2,1,3]
Output: [1,2,3]

Example 3:

Input: root = []
Output: []
Explanation: Input is an empty tree. Output is also an empty Linked List.

Example 4:

Input: root = [1]
Output: [1]

 

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000
  • All the values of the tree are unique.

Companies:
Facebook, Microsoft, Google, Amazon, Expedia

Related Topics:
Linked List, Divide and Conquer, Tree

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
public:
    Node* treeToDoublyList(Node* root) {
        if (!root) return NULL;
        auto left = treeToDoublyList(root->left), right = treeToDoublyList(root->right);
        root->left = left ? left->left : (right ? right->left : root);
        root->right = right ? right : (left ? left : root);
        if (left) {
            left->left->right = root;
            left->left = right ? right->left : root;
        }
        if (right) {
            right->left->right = left ? left : root;
            right->left = root;
        }
        return left ? left : root;
    }
};