Leetcode 426 Convert Binary Search Tree to Sorted Doubly Linked List
The left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list.
Approach 1: DFS InOrder + Recursion
Standard inorder recursion follows left -> node -> right order.
Processing here is basically to link the previous node with the current one, and because of that one has to track the last node which is the largest node in a new doubly linked list so far.
class Solution {
Node first = null;
Node last = null;
public Node treeToDoublyList(Node root) {
if (root == null) return null;
helper(root);
// the successor node of last node is first node.
last.right = first;
// the predecessor of first node is last node.
first.left = last;
return first;
}
public void helper(Node node){ // using InOrder DFS
if(node == null)
return;
helper(node.left);
if(first == null){
first = node;
}else{
// the successor of last node is current node
last.right = node;
// the predecessor of current node is last node;
node.left = last;
}
//current node becomes the last node
last = node;
helper(node.right);
}
}
Time complexity : O(N) since each node is processed exactly once.
Space complexity : O(N), We have to keep a recursion stack of the size of the tree height, which is O(logN) for the best case of completely balanced tree and O(N) for the worst case of completely unbalanced tree.