Convert Binary Search Tree to Sorted Doubly Linked List

lc 426 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.

/*
// 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 dummy = new Node(-1, null, null);
        Node prev = dummy;
        Stack<Node> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while(root != null) {
                stack.push(root);
                root = root.left;
            }
            Node cur = stack.pop();
            prev.right = cur;
            cur.left = prev;
            prev = cur;
            root = cur.right;
        }
        prev.right = dummy.right;
        dummy.right.left = prev;
        return dummy.right;
    }
}

results matching ""

    No results matching ""