Flatten binary tree to linked list | Practice | GeeksforGeeks

Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder.
Example 1:
Input : 
          1
        /   \
       2     5
      / \     \
     3   4     6
Output :
1 2 3 4 5 6 
Explanation: 
After flattening, the tree looks 
like this
    1
     \
      2
       \
        3
         \
          4
           \
            5
             \
              6 
Here, left of each node points 
to NULL and right contains the 
next node in preorder.The inorder 
traversal of this flattened tree 
is 1 2 3 4 5 6.
Example 2:
Input :
        1
       / \
      3   4
         /
        2
         \
          5 
Output : 
1 3 4 2 5  
Explanation : 
After flattening, the tree looks 
like this 
     1
      \
       3
        \
         4
          \
           2
            \ 
             5 
Here, left of each node points 
to NULL and right contains the 
next node in preorder.The inorder 
traversal of this flattened tree 
is 1 3 4 2 5.
0
rohanmeher1642 weeks ago
// java solution
 
class Solution{   public static void flatten(Node root)   {     if(root==null) return;         while(root!=null)    {        if(root.left!=null)        {            Node curr=root.left;                       while(curr.right!=null) curr=curr.right;            curr.right=root.right;            root.right=root.left;            root.left=null;        }        root=root.right;    }   }}
0
vivekroxstar92 weeks ago
JavaScript Solution
class Solution {
    constructor(){
        this.prev=null;
    }
  	flatten(root){
  		//code here
  		if(root===null)return;
        this.flatten(root.right);
        this.flatten(root.left);
        root.right=this.prev;
        root.left=null;
        this.prev=root;
        return root;
  	}
}
0
adarshgupta4013 weeks ago
Java-Most optimal and Easiest Approach-
class Solution
{
    public static void flatten(Node root)
    {
        Node cur = root;
		while (cur != null)
		{
			if(cur.left != null)
			{
				Node pre = cur.left;
				while(pre.right != null)
				{
					pre = pre.right;
				}
				pre.right = cur.right;
				cur.right = cur.left;
				cur.left = null;
			}
			cur = cur.right;
		}

    }
}
0
singhashu19993 weeks ago
class Solution{   public:      void flatten(Node *root)   {       //code here       map<int,queue<Node*>> mp;       vector<int> p;              Node* temp = root;       stack<Node*> st;       st.push(root);              while(st.empty() == false)       {           temp = st.top();           st.pop();           if(temp != root)           {           mp[temp->key].push(temp);           }           p.push_back(temp->key);                      if(temp->right)           {               st.push(temp->right);           }           if(temp->left)           {               st.push(temp->left);           }       }       //cout << p.size() << endl;       int i=0;       temp = root;       while(i < p.size())       {           if(i == p.size() - 1)           {               temp->left = NULL;               temp->right = NULL;               break;           }           //cout << p[i+1] << endl;           temp->left = NULL;           temp->right = mp[p[i+1]].front();           mp[p[i+1]].pop();           temp = temp->right;           i += 1;       }          }};
0
amishasahu3283 weeks ago
// Morris Traversal
// TC-> O(n) | SC->O(1)
    void flatten(Node *root)
    {
        if(!root) return;
        Node *curr = root;
        while(curr)
        {
            if(curr->left != NULL)
            {
                Node *prev = curr->left;
                while(prev->right)
                    prev = prev->right;
            
                prev->right = curr->right;
                curr->right = curr->left;
            }
            curr->left = NULL;
            curr = curr->right;
            
        }
    }
0
ayushtiwari264023 weeks ago
class Solution{   public static void flatten(Node root)   {       if(root==null) return;       if(root.left==null){           flatten(root.right);           return;       }else{           Node left = root.left;           root.left=null;           Node right = root.right;           flatten(left);           flatten(right);           root.right = left;           while(root.right!=null) root=root.right;           root.right=right;           return;       }   }}
0
dileeprajoriya20193 weeks ago
Simple Solution Using Morris Traversal--→(c++)
 
void flatten(Node *root)   {       Node *curr = root;              while(curr)       {           if(curr->left)           {               Node *pred = curr->left;               while(pred->right != NULL)               {                   pred = pred->right;               }                              pred->right = curr->right;               curr->right = curr->left;               curr->left = NULL;                                         }                      curr = curr->right;       }   }
+1
akashmr10961 month ago
  public static void flatten(Node root)
    {
        flattenUtil(root);
    }
    
    private static Node flattenUtil(Node root) {
        if (root == null) {
            return null;
        }
        
        Node n1 = flattenUtil(root.left);
        Node rightHead = flattenUtil(root.right);
        Node leftHead = n1;
        root.left = null;
        
        Node tail = root;
        while(n1 != null) {
            tail = n1;
            n1 = n1.right;
        }
        
        if (tail != root) {
            root.right = leftHead;
        }
        tail.right = rightHead;
        return root;
    }
0
mukulmishra24101 month ago
// USING MORRIS TRAVERSAL 
 
void flatten(Node *root)   {
// take a current on the root node       Node* curr = root;
// run the loop till the current is not NULL       while(curr != NULL){
// if current node does left exist            if(curr -> left)           {
// find the predecessor of current node               Node* pred = curr -> left;               while(pred -> right){                   pred = pred -> right;               }
// link the predecessor node with the current node's right                   pred -> right = curr -> right;
//link the  current node's right with current node's left                   curr -> right = curr -> left;
// mark current node's left as NULL                   curr -> left = NULL;           }
// if current node's left does not exist, point it to the current node's right           curr = curr -> right;       }   }
0
vasukapoor07992 months ago
Java Solution
 public static Node flat(Node node){       if(node == null) return null;              // Returning the tails        Node ltail = flat(node.left);        Node rtail = flat(node.right);              // Here we are checking if we have leftSubtree because if ltail is null then       // No node is present in leftSubtree       if(ltail != null){           ltail.right = node.right;           node.right = node.left;           node.left = null;       }              // Leaf Node       if(rtail == null && ltail == null) return node;              // if rightSubtree is not present then rtail = null have to return ltail        return rtail != null? rtail: ltail;   }         public static void flatten(Node root)   {       flat(root);   }
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.