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.
Let's take the following BST as an example, it may help you understand the problem better:
// 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) {
Node head=null;
Node tail=null;
Node temp=root;
Stack st=new Stack();
while(!st.isEmpty()||temp!=null){
if(temp!=null ){
st.push(temp);
temp=temp.left;
}else{
Node node1=st.pop();
temp=node1.right;
if(head==null){
head=tail=node1;
}else{
tail.right=node1;
node1.left=tail;
tail=tail.right;
}
}
}
if(head!=null){
head.left=tail;
}
if(tail!=null){
tail.right=head;
}
return head;
}
}
No comments:
Post a Comment