Make Binary Tree From Linked List | Practice | GeeksforGeeks

Given a Linked List Representation of Complete Binary Tree. The task is to construct the Binary tree.
Note : The complete binary tree is represented as a linked list in a way where if root node is stored at position i, its left, and right children are stored at position 2*i+1, 2*i+2 respectively.
 


Example 1:
Input:
N = 5
K = 1->2->3->4->5
Output: 1 2 3 4 5
Explanation: The tree would look like
      1
    /   \
   2     3
 /  \
4   5
Now, the level order traversal of
the above tree is 1 2 3 4 5.

Example 2:
Input:
N = 5
K = 5->4->3->2->1
Output: 5 4 3 2 1
Explanation: The tree would look like
     5
   /  \
  4    3
 / \
2    1
Now, the level order traversal of
the above tree is 5 4 3 2 1.
Your Task:
The task is to complete the function convert() which takes head of linked list and root of the tree as the reference. The driver code prints the level order.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Note: H is the height of the tree and this space is used implicitly for recursion stack.
Constraints:
1 <= N <= 105
1 <= Ki <= 105
0
codepk3 weeks ago
plz anybody optimize this......
 
 
 
TreeNode * llToBt(vector<int> v,int sizeofll,int index){   if(index>=sizeofll) { return NULL;}   TreeNode* root =new TreeNode(v[index]);   root->left=llToBt(v,sizeofll,index*2+1);   root->right=llToBt(v,sizeofll,index*2+2);   return root;}void convert(Node *head, TreeNode *&root) { if(head==NULL) return; vector<int> v; while(head) {v.push_back(head->data);head=head->next; } int index=0; root=llToBt(v,v.size(),index);}
0
abrajput15063 weeks ago
void convert(Node *head, TreeNode *&root) {
    // Your code here
    queue<TreeNode*> q;
    root = new TreeNode(head->data);
    q.push(root);
    
    Node* ptr = head->next;
    while(!q.empty() && ptr){
        TreeNode* temp = q.front();
        q.pop();
        
        if(ptr){
            temp->left = new TreeNode(ptr->data);
            q.push(temp->left);
            ptr = ptr->next;
        }
        
        if(ptr){
            temp->right = new TreeNode(ptr->data);
            q.push(temp->right);
            ptr = ptr->next;
        }
        
    }
}

0
crawler1 month ago
void huihui(TreeNode *&root, int i, vector<int> &values){
    if(root){
        int left = 2*i + 1;
        int right = 2*i + 2;
        if(left < values.size()){
            root->left = new TreeNode(values[left]);
        }
        if(right < values.size()){
            root->right = new TreeNode(values[right]);
        }
        huihui(root->left, 2*i+1, values);
        huihui(root->right, 2*i+2, values);
    }
}
void convert(Node *head, TreeNode *&root) {
    vector<int> values;
    Node *iter = head;
    while(iter){
        values.push_back(iter->data);
        iter = iter->next;
    }
    if(!values.size())
        root = nullptr;
    else{
        root = new TreeNode(values[0]);
        int i = 0;
        huihui(root,i, values);
    }
}
0
dvirbarel2 months ago
C#
 
            if(head == null)           {               return null;           }                      var q = new Queue<Node>();           var root = new Node(head.val);           q.Enqueue(root);                      while(head.next != null){               head = head.next;               var parent = q.Dequeue();                     parent.left = new Node(head.val);               if(head.next != null){                 head = head.next;                 parent.right = new Node(head.val);               }               q.Enqueue(parent.left);               q.Enqueue(parent.right);           }                      return root;
 
0
mridulbhaskarabc2 months ago
# Contributed By: Mridul Bhaskar
def convert(head):
    root = None
    temp = None
  
    # code here
    if(head is None):
        return None
    root = Tree(head.data)
    temp = root
    while(head.next):
        
        
        head = head.next
        root.left = Tree(head.data)
            
            
        if(head.next):
            
            head = head.next
            root.right = Tree(head.data)
        root = root.left
            
    return temp
 
+1
shivank9112 months ago
JAVA SOLUTION -O(N) COMPLEXITY
public static Tree convert(Node head, Tree node) {       // add code here.}       ArrayDeque<Tree> que=new ArrayDeque<>();       Tree root=new Tree(head.data);       que.add(root);       while(que.size()>0){           int size=que.size();           while(size-->0){               Tree temp=que.remove();               if(head.next!=null){                   head=head.next;                   Tree left=new Tree(head.data);                   temp.left=left;                   que.add(left);               }               if(head.next!=null){                   head=head.next;                   Tree right=new Tree(head.data);                   temp.right=right;                   que.add(right);               }                          }       }       return root;          }
0
hamidnourashraf2 months ago
def convert(head):
    root = Tree(head.data)
    stack = [root]
    while head:
        curr_node = stack.pop(0)
        head = head.next
        if head:
            curr_node.left = Tree(head.data)
            stack.append(curr_node.left)
            head = head.next
            if head:
                curr_node.right = Tree(head.data)
                stack.append(curr_node.right)
            else:
                break
        else:
            break

    return root
0
abhhishek2 months ago
class GfG 
{
    //Function to make binary tree from linked list.
    public static Tree convert(Node head, Tree node) {
        if (head == null)
        {
            node = null;
            return null;
        }
        Tree res = new Tree(head.data);
        head = head.next;
        Queue<Tree> queue = new LinkedList<>();
        queue.offer(res);
        while(!queue.isEmpty()){
            int n=queue.size();
            
            while(n-- > 0){
                Tree temp = queue.peek();
                if(head!=null){
                    temp.left = new Tree(head.data);
                    queue.offer(temp.left);
                    head = head.next;
                }
                if(head!=null){
                    temp.right = new Tree(head.data);
                    queue.offer(temp.right);
                    head = head.next;
                }
                queue.poll();
            }
        }
        return res;
    }
}
+4
mohankumarit20012 months ago
Found a loop hole lol!
void convert(Node *head, TreeNode *&root) {
    if(!head)return;
    root = new TreeNode(head->data);
    convert(head->next,root->left);
}
0
rogueninjaofkonoha3 months ago
Without Recursion:2 queues approach 
 
public static Tree convert(Node head, Tree node) {
        // add code here.}
        
        Queue<Tree> q1 = new LinkedList<Tree>();
        Queue<Tree> q2 = new LinkedList<Tree>();
        
        Tree sm = new Tree(head.data);
        
        q1.add(sm);
        head = head.next;
        
        while(!q1.isEmpty() || !q2.isEmpty()) {
            while(!q1.isEmpty()) {
                Tree temp = q1.poll();
                if(head!=null) {
                    temp.left = new Tree(head.data);
                    head = head.next;
                    q1.add(temp.left);
                }
                if(head!=null) {
                    temp.right = new Tree(head.data);
                    head = head.next;
                    q1.add(temp.right);
                    
                }
            }
            while(!q2.isEmpty()) {
                Tree temp = q2.poll();
                if(head!=null) {
                    temp.left = new Tree(head.data);
                    head = head.next;
                    q1.add(temp.left);
                }
                if(head!=null) {
                    temp.right = new Tree(head.data);
                    head = head.next;
                    q1.add(temp.right);
                    
                }
            }
        }
        node = sm;
        return node;
     
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.