Convert a given Binary Tree to Doubly Linked List
Given a Binary Tree (Bt), convert it to a Doubly Linked List(DLL).
The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL.
The order of nodes in DLL must be same as Inorder of the given Binary Tree.
The first node of Inorder traversal (left most node in BT) must be head node of the DLL.
Solution
O(n) time complexity
TreeNode{
int val;
TreeNode left, right;
}
public static TreeNode convert(TreeNode root){
if(root==null) return root;
TreeNode[] headtail=new TreeNode[2];//head, tail
helper(root, headtail);
while(root.left!=null) root=root.left;
return root;
}
public static void helper(TreeNode root, TreeNode[] headtail){
if(root.left==null&&root.right==null){
headtail[0]=root;
headtail[1]=root;
return;
}
if(root.left!=null){
helper(root.left, headtail);
headtail[1].right=root;
root.left=headtail[1];
}else headtail[0]=root;
TreeNode tmp=headtail[0];
if(root.right!=null){
helper(root.right, headtail);
headtail[0].left=root;
root.right=headtail[0];
}else headtail[1]=root;
headtail[0]=tmp;
}
public static void main(String[] args)
{
TreeNode root=new TreeNode(5);
root.left=new TreeNode(2);
root.right=new TreeNode(7);
root.right.left=new TreeNode(6);
root.left.left=new TreeNode(1);
root.left.right=new TreeNode(3);
root.left.right.right=new TreeNode(4);
TreeNode pt=convert(root);
while(pt!=null){
System.out.print(pt.val+"\t");
pt=pt.right;
}
}