MrainW's Home

All things come to those who wait!

0%

LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List

Question

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.

https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/

Example 1:

1
2
3
4
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:

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

Solution

  • Solution1 – recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
Node pre = null, head = null;
public Node treeToDoublyList(Node root) {
if (root == null) return root;
inorderTraversal(root);
head.left = pre;
pre.right = head;
return head;
}
private void inorderTraversal(Node root){
if(root == null) return;
inorderTraversal(root.left); //left
if(head == null) head = root;
if(pre != null) pre.right = root; //root
root.left = pre;
pre = root;
inorderTraversal(root.right); //right
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels