@@ -0,0 +1,2198 @@
+package tree.bst.in_order;%0A%0Aimport public_class.Node;%0A%0Apublic class Q426ConvertBinarySearchTreeToSortedDoublyLinkedList %7B%0A%0A    //Difficulty: medium%0A    //TAG: Facebook%0A    //TAG: bst%0A    //TAG: inorder%0A%0A    /**%0A     * 426. Convert Binary Search Tree to Sorted Doubly Linked List%0A     * 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.%0A     *%0A     * Let's take the following BST as an example, it may help you understand the problem better:%0A     *%0A     *%0A     *%0A     *%0A     *%0A     * We want to transform this BST into a circular doubly linked list. Each node in a doubly linked list has a predecessor and successor. 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.%0A     *%0A     * The figure below shows the circular doubly linked list for the BST above. The %22head%22 symbol means the node it points to is the smallest element of the linked list.%0A     *%0A     *%0A     *%0A     *%0A     *%0A     * Specifically, 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. We should return the pointer to the first element of the linked list.%0A     *%0A     * The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.%0A     *%0A     *%0A     */%0A%0A    /*%0A    Solution:%0A%0A    inorder traversal, similar to reverse linkedList, and finally link head and tail node%0A%0A    Time: O(n)%0A    Space: O(n)%0A     */%0A%0A    private Node pre, head;%0A    public Node treeToDoublyList(Node root) %7B%0A        if (root == null) return root;%0A        inorder(root);%0A        head.left = pre;%0A        pre.right = head;%0A        return head;%0A    %7D%0A%0A    private void inorder(Node node) %7B%0A        if (node == null) return;%0A        inorder(node.left);%0A        node.left = pre;%0A        if (pre != null) pre.right = node;%0A        else head = node;%0A        pre = node;%0A        inorder(node.right);%0A    %7D%0A%0A%7D%0A

426. Convert Binary Search Tree to Sorted Doubly Linked List