> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/oj-practices/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/oj-practices/chapter1/linked-list/426-convert-binary-search-tree-to-sorted-doubly-linked-list.md).

# 426     Convert Binary Search Tree to Sorted Doubly Linked List

## 426. [Convert Binary Search Tree to Sorted Doubly Linked List](https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/description/)

## 1. Question

Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.

## 2. Implementation

思路: 通过Inorder traversal遍历Binary Search Tree, 同时维护preNode, 将preNode 和 当前的node像double linked list那样连起来。最后再将double linked list的head和tail连起来即可

```java
/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return root;
        }

        Node[] preNode = new Node[1];
        Node dummy = new Node(0, null, null);
        preNode[0] = dummy;

        inorderTraverse(root, preNode);
        preNode[0].right = dummy.right;
        dummy.right.left = preNode[0];
        return dummy.right;
    }

    public void inorderTraverse(Node node, Node[] preNode) {
        if (node == null) {
            return;
        }

        inorderTraverse(node.left, preNode);
        preNode[0].right = node;
        node.left = preNode[0];
        preNode[0] = node;
        inorderTraverse(node.right, preNode);
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(h), 递归深度是树的高度
