Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, August 30, 2017

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;
}

0 Comments:

Post a Comment

Stats