Convert a binary search tree to doubly linked list with in-order traversal.
public DoublyListNode bstToDoublyList(TreeNode root) {
if (root == null) {
return null;
}
DoublyListNode dummy = new DoublyListNode(-1);
DoublyListNode formmer = null;
DoublyListNode latter = null;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode tmp = stack.pop();
cur = tmp.right;
if (formmer == null) {
formmer = new DoublyListNode(tmp.val);
dummy.next = formmer;
continue;
} else {
latter = new DoublyListNode(tmp.val);
}
formmer.next = latter;
latter.prev = formmer;
formmer = latter;
}
return dummy.next;
}