Convert Linked list to tree
Explanation:
Perform BFS and start adding data of LL to tree..
Code:
public static Tree convert(Node head,Tree node){
Deque<Tree> q=new ArrayDeque<Tree>();
node=new Tree(head.data);
q.add(node);
head=head.next;
while(!q.isEmpty() && head!=null)
{
Tree t=q.removeFirst();
t.left=new Tree(head.data);
head=head.next;
if(head==null)
break;
t.right=new Tree(head.data);
head=head.next;
q.add(t.left);
q.add(t.right);
}
return node;
}
Perform BFS and start adding data of LL to tree..
Code:
public static Tree convert(Node head,Tree node){
Deque<Tree> q=new ArrayDeque<Tree>();
node=new Tree(head.data);
q.add(node);
head=head.next;
while(!q.isEmpty() && head!=null)
{
Tree t=q.removeFirst();
t.left=new Tree(head.data);
head=head.next;
if(head==null)
break;
t.right=new Tree(head.data);
head=head.next;
q.add(t.left);
q.add(t.right);
}
return node;
}
0 Comments:
Post a Comment