Modify a Binary Tree by shifting all nodes to as far right as possible

Given a binary tree, the task is to print the inorder traversal of the modified tree obtained after shifting all the nodes of the given tree to as far right as possible, while maintaining the relative ordering in each level.
Examples:
Input: Below is the given Tree:
           1
          /  \
        2   3
      /  \    \
     4   5     6
Output: 2 4 1 5 3 6
Explanation: The tree obtained after shifting all nodes to far right is as follows:
           1
          /  \
         2   3
         \   /  \
         4 5   6Input: Below is the given Tree:
          1
         /
        2
      /   \
    3    4
        /  \
       5    6
Output: 1 3 2 5 4 6
Explanation:
          1
           \
           2
         /   \
        3    4
           /  \
          5   6
Approach: The idea to solve the given problem is to store the nodes of a level from right to left using a stack and existing nodes of the next level using a queue and connect the nodes at valid positions using Level Order Traversal. Follow the steps below to solve the problem:
- Initialize a stack S to store the sequence of nodes of a level of a Binary Tree from right to left.
- Initialize a queue Q to store the existing nodes of a level of a Binary Tree.
- If the right child of root exists, push it into queue Q. Vacate the right child.
- If the left child of root exists, push it into queue Q. Vacate the left child.
- Push root into the stack S.
- Perform Level Order Traversal on the Binary Tree and perform the following steps:
- If the right child of the node at the top of the stack is vacant, set the node at the front of the queue as the right child.
- Otherwise, repeat the above step for the left child. Pop the node from the top of the stack.
- Add the left and right child of the node at the front of the queue, into the queue.
- Store the sequence of nodes in the next level from right to left in the Stack.
- After completing the above steps, print the inorder traversal of the modified tree.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Structure of a Tree nodestruct TreeNode {Â Â Â Â int val = 0;Â Â Â Â TreeNode* left;Â Â Â Â TreeNode* right;Â
    // Constructor    TreeNode(int x)    {        val = x;        left = right = NULL;    }};Â
// Function to print Inorder// Traversal of a Binary Treevoid printTree(TreeNode* root){Â Â Â Â if (!root)Â Â Â Â Â Â Â Â return;Â
    // Traverse left child    printTree(root->left);Â
    // Print current node    cout << root->val << " ";Â
    // Traverse right child    printTree(root->right);}Â
// Function to shift all nodes of the// given Binary Tree to as far as// right possibleTreeNode* shiftRight(TreeNode* root){Â
    // If tree is empty    if (!root)        return NULL;Â
    stack<TreeNode*> st;    queue<TreeNode*> q;Â
    // If right child exists    if (root->right)        q.push(root->right);Â
    root->right = NULL;Â
    // If left child exists    if (root->left)        q.push(root->left);Â
    root->left = NULL;Â
    // Push current node into stack    st.push(root);Â
    while (!q.empty()) {Â
        // Count valid existing nodes        // in current level        int n = q.size();        stack<TreeNode*> temp;Â
        // Iterate existing nodes        // in the current level        while (n--) {Â
            // If no right child exists            if (!st.top()->right)Â
                // Set the rightmost                // vacant node                st.top()->right = q.front();Â
            // If no left child exists            else {Â
                // Set rightmost vacant node                st.top()->left = q.front();Â
                // Remove the node as both                // child nodes are occupied                st.pop();            }Â
            // If r?ight child exist            if (q.front()->right)Â
                // Push into the queue                q.push(q.front()->right);Â
            // Vacate right child            q.front()->right = NULL;Â
            // If left child exists            if (q.front()->left)Â
                // Push into the queue                q.push(q.front()->left);Â
            // Vacate left child            q.front()->left = NULL;Â
            // Add the node to stack to            // maintain sequence of nodes            // present in the level            temp.push(q.front());            q.pop();        }Â
        while (!st.empty())            st.pop();Â
        // Add nodes of the next        // level into the stack st        while (!temp.empty()) {Â
            st.push(temp.top());            temp.pop();        }    }Â
    // Return the root of the    // modified Tree    return root;}Â
// Driver Codeint main(){Â
    TreeNode* root = new TreeNode(1);    root->left = new TreeNode(2);    root->right = new TreeNode(3);    root->left->left = new TreeNode(4);    root->left->right = new TreeNode(5);    root->right->right = new TreeNode(6);Â
    // Function Call    root = shiftRight(root);Â
    // Print the inOrder Traversal    printTree(root);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;public class Main{       // Class containing left and    // right child of current    // node and key value    static class TreeNode {                 public int val;        public TreeNode left, right;                 public TreeNode(int x)        {            val = x;            left = right = null;        }    }         // Function to print Inorder    // Traversal of a Binary Tree    static void printTree(TreeNode root)    {        if (root == null)            return;           // Traverse left child        printTree(root.left);           // Print current node        System.out.print(root.val + " ");           // Traverse right child        printTree(root.right);    }       // Function to shift all nodes of the    // given Binary Tree to as far as    // right possible    static TreeNode shiftRight(TreeNode root)    {           // If tree is empty        if (root == null)            return null;           Stack<TreeNode> st = new Stack<TreeNode>();        Queue<TreeNode> q = new LinkedList<>();           // If right child exists        if (root.right != null)            q.add(root.right);           root.right = null;           // If left child exists        if (root.left != null)            q.add(root.left);           root.left = null;           // Push current node into stack        st.push(root);           while (q.size() > 0) {               // Count valid existing nodes            // in current level            int n = q.size();            Stack<TreeNode> temp = new Stack<TreeNode>();               // Iterate existing nodes            // in the current level            while (n-- > 0) {                   // If no right child exists                if (((TreeNode)st.peek()).right == null)                       // Set the rightmost                    // vacant node                    ((TreeNode)st.peek()).right = (TreeNode)q.peek();                   // If no left child exists                else {                       // Set rightmost vacant node                    ((TreeNode)st.peek()).left = (TreeNode)q.peek();                       // Remove the node as both                    // child nodes are occupied                    st.pop();                }                   // If r?ight child exist                if (((TreeNode)q.peek()).right != null)                       // Push into the queue                    q.add(((TreeNode)q.peek()).right);                   // Vacate right child                ((TreeNode)q.peek()).right = null;                   // If left child exists                if (((TreeNode)q.peek()).left != null)                       // Push into the queue                    q.add(((TreeNode)q.peek()).left);                   // Vacate left child                ((TreeNode)q.peek()).left = null;                   // Add the node to stack to                // maintain sequence of nodes                // present in the level                temp.push(((TreeNode)q.peek()));                q.remove();            }               while (st.size() > 0)                st.pop();               // Add nodes of the next            // level into the stack st            while (temp.size() > 0) {                   st.push(temp.peek());                temp.pop();            }        }           // Return the root of the        // modified Tree        return root;    }         public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.left = new TreeNode(4);        root.left.right = new TreeNode(5);        root.right.right = new TreeNode(6);               // Function Call        root = shiftRight(root);               // Print the inOrder Traversal        printTree(root);    }}Â
// This code is contributed by suresh07. |
Python3
# Python 3 program for the above approachÂ
# Structure of a Tree nodeclass TreeNode:Â
    def __init__(self,val):        self.val = val        self.left = None        self.right = NoneÂ
# Function to print Inorder# Traversal of a Binary Treedef printTree(root):Â Â Â Â if (root == None):Â Â Â Â Â Â Â Â returnÂ
    # Traverse left child    printTree(root.left)Â
    # Print current node    print(root.val,end = " ")Â
    # Traverse right child    printTree(root.right)Â
# Function to shift all nodes of the# given Binary Tree to as far as# right possibledef shiftRight(root):       # If tree is empty    if (root == None):        return NoneÂ
    st = [] #stack    q = [] # queueÂ
    # If right child exists    if (root.right):        q.append(root.right)Â
    root.right = NoneÂ
    # If left child exists    if (root.left):        q.append(root.left)Â
    root.left = NoneÂ
    # Push current node into stack    st.append(root)Â
    while (len(q) > 0):               # Count valid existing nodes        # in current level        n = len(q)        temp = []Â
        # Iterate existing nodes        # in the current level        while (n > 0 and len(st) > 0 and len(q) > 0):                       # If no right child exists            if (st[len(st) - 1].right == None):Â
                # Set the rightmost                # vacant node                st[len(st) - 1].right = q[0]Â
            # If no left child exists            else:                               # Set rightmost vacant node                st[len(st) - 1].left = q[0]Â
                # Remove the node as both                # child nodes are occupied                st = st[:-1]Â
            # If r?ight child exist            if (q[0].right):                               # Push into the queue                q.append(q[0].right)Â
            # Vacate right child            q[0].right = NoneÂ
            # If left child exists            if (q[0].left):Â
                # Push into the queue                q.append(q[0].left)Â
            # Vacate left child            q[0].left = NoneÂ
            # Add the node to stack to            # maintain sequence of nodes            # present in the level            temp.append(q[0])            q = q[1:]Â
        while (len(st) > 0):            st = st[:-1]Â
        # Add nodes of the next        # level into the stack st        while(len(temp)>0):            st.append(temp[len(temp)-1])            temp = temp[:-1]Â
    # Return the root of the    # modified Tree    return rootÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â root = TreeNode(1)Â Â Â Â root.left = TreeNode(2)Â Â Â Â root.right = TreeNode(3)Â Â Â Â root.left.left = TreeNode(4)Â Â Â Â root.left.right = TreeNode(5)Â Â Â Â root.right.right = TreeNode(6)Â
    # Function Call    root = shiftRight(root)Â
    # Print the inOrder Traversal    printTree(root)         # This code is contributed by SURENDRA_GANGWAR. |
C#
// C# program for the above approachusing System;using System.Collections;class GFG {         // Class containing left and    // right child of current    // node and key value    class TreeNode {                public int val;        public TreeNode left, right;                public TreeNode(int x)        {            val = x;            left = right = null;        }    }         // Function to print Inorder    // Traversal of a Binary Tree    static void printTree(TreeNode root)    {        if (root == null)            return;          // Traverse left child        printTree(root.left);          // Print current node        Console.Write(root.val + " ");          // Traverse right child        printTree(root.right);    }      // Function to shift all nodes of the    // given Binary Tree to as far as    // right possible    static TreeNode shiftRight(TreeNode root)    {          // If tree is empty        if (root == null)            return null;          Stack st = new Stack();        Queue q = new Queue();          // If right child exists        if (root.right != null)            q.Enqueue(root.right);          root.right = null;          // If left child exists        if (root.left != null)            q.Enqueue(root.left);          root.left = null;          // Push current node into stack        st.Push(root);          while (q.Count > 0) {              // Count valid existing nodes            // in current level            int n = q.Count;            Stack temp = new Stack();              // Iterate existing nodes            // in the current level            while (n-- > 0) {                  // If no right child exists                if (((TreeNode)st.Peek()).right == null)                      // Set the rightmost                    // vacant node                    ((TreeNode)st.Peek()).right = (TreeNode)q.Peek();                  // If no left child exists                else {                      // Set rightmost vacant node                    ((TreeNode)st.Peek()).left = (TreeNode)q.Peek();                      // Remove the node as both                    // child nodes are occupied                    st.Pop();                }                  // If r?ight child exist                if (((TreeNode)q.Peek()).right != null)                      // Push into the queue                    q.Enqueue(((TreeNode)q.Peek()).right);                  // Vacate right child                ((TreeNode)q.Peek()).right = null;                  // If left child exists                if (((TreeNode)q.Peek()).left != null)                      // Push into the queue                    q.Enqueue(((TreeNode)q.Peek()).left);                  // Vacate left child                ((TreeNode)q.Peek()).left = null;                  // Add the node to stack to                // maintain sequence of nodes                // present in the level                temp.Push(((TreeNode)q.Peek()));                q.Dequeue();            }              while (st.Count > 0)                st.Pop();              // Add nodes of the next            // level into the stack st            while (temp.Count > 0) {                  st.Push(temp.Peek());                temp.Pop();            }        }          // Return the root of the        // modified Tree        return root;    }       static void Main() {    TreeNode root = new TreeNode(1);    root.left = new TreeNode(2);    root.right = new TreeNode(3);    root.left.left = new TreeNode(4);    root.left.right = new TreeNode(5);    root.right.right = new TreeNode(6);      // Function Call    root = shiftRight(root);      // Print the inOrder Traversal    printTree(root);  }}Â
// This code is contributed by decode2207. |
Javascript
<script>Â
    // JavaScript program for the above approach         class TreeNode    {        constructor(x) {           this.left = null;           this.right = null;           this.val = x;        }    }         // Function to print Inorder    // Traversal of a Binary Tree    function printTree(root)    {        if (!root)            return;Â
        // Traverse left child        printTree(root.left);Â
        // Print current node        document.write(root.val + " ");Â
        // Traverse right child        printTree(root.right);    }Â
    // Function to shift all nodes of the    // given Binary Tree to as far as    // right possible    function shiftRight(root)    {Â
        // If tree is empty        if (root == null)            return null;Â
        let st = [];        let q = [];Â
        // If right child exists        if (root.right)            q.push(root.right);Â
        root.right = null;Â
        // If left child exists        if (root.left != null)            q.push(root.left);Â
        root.left = null;Â
        // Push current node into stack        st.push(root);Â
        while (q.length > 0) {Â
            // Count valid existing nodes            // in current level            let n = q.length;            let temp = [];Â
            // Iterate existing nodes            // in the current level            while (n-- > 0) {Â
                // If no right child exists                if (st[st.length - 1].right == null)Â
                    // Set the rightmost                    // vacant node                    st[st.length - 1].right = q[0];Â
                // If no left child exists                else {Â
                    // Set rightmost vacant node                    st[st.length - 1].left = q[0];Â
                    // Remove the node as both                    // child nodes are occupied                    st.pop();                }Â
                // If r?ight child exist                if (q[0].right != null)Â
                    // Push into the queue                    q.push(q[0].right);Â
                // Vacate right child                q[0].right = null;Â
                // If left child exists                if (q[0].left != null)Â
                    // Push into the queue                    q.push(q[0].left);Â
                // Vacate left child                q[0].left = null;Â
                // Add the node to stack to                // maintain sequence of nodes                // present in the level                temp.push(q[0]);                q.shift();            }Â
            while (st.length > 0)                st.pop();Â
            // Add nodes of the next            // level into the stack st            while (temp.length > 0) {Â
                st.push(temp[temp.length - 1]);                temp.pop();            }        }Â
        // Return the root of the        // modified Tree        return root;    }         let root = new TreeNode(1);    root.left = new TreeNode(2);    root.right = new TreeNode(3);    root.left.left = new TreeNode(4);    root.left.right = new TreeNode(5);    root.right.right = new TreeNode(6);      // Function Call    root = shiftRight(root);      // Print the inOrder Traversal    printTree(root);     </script> |
2 4 1 5 3 6
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach 2: (Using hashmap)
1. Store the levels and corresponding tree nodes.
2.And then greedily assign the nodes first as a right child and then as left in pairs of 2.
C++
// CPP program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std;Â
// Structure of a Tree nodestruct TreeNode {Â Â Â Â int val = 0;Â Â Â Â TreeNode* left;Â Â Â Â TreeNode* right;Â
    // Constructor    TreeNode(int x)    {        val = x;        left = right = NULL;    }};Â
// Function to print Inorder// Traversal of a Binary Treevoid printTree(TreeNode* root){Â Â Â Â if (!root)Â Â Â Â Â Â Â Â return;Â
    // Traverse left child    printTree(root->left);Â
    // Print current node    cout << root->val << " ";Â
    // Traverse right child    printTree(root->right);}Â
void dfsit(TreeNode* rt, int key,           map<int, vector<TreeNode*> >& mp){    if (!rt) {        return;    }    mp[key].push_back(rt);    dfsit(rt->right, key + 1, mp);    dfsit(rt->left, key + 1, mp);    rt->left = NULL;    rt->right = NULL;}Â
TreeNode* shiftRight(TreeNode* root){Â Â Â Â TreeNode* tmp = root;Â Â Â Â map<int, vector<TreeNode*> > mp;Â Â Â Â int i = 0;Â
    dfsit(root, 0, mp);    int n = mp.size();    TreeNode* cur = new TreeNode(-1);         queue<TreeNode*> st;    st.push(cur);Â
  while (i < n) {        vector<TreeNode*> nd = mp[i];        int j = 0;        queue<TreeNode*> tmp;        while (j < nd.size()) {            auto r = st.front();            st.pop();            r->right = nd[j];            tmp.push(nd[j]);            j++;            if (j < nd.size()) {                r->left = nd[j];                tmp.push(nd[j]);                j++;            }        }        st = tmp;        i++;    }Â
    return cur->right;}Â
// Driver Codeint main(){Â
    TreeNode* root = new TreeNode(1);    root->left = new TreeNode(2);    root->right = new TreeNode(3);    root->left->left = new TreeNode(4);    root->left->right = new TreeNode(5);    root->right->right = new TreeNode(6);Â
    // Function Call    root = shiftRight(root);Â
    // Print the inOrder Traversal    printTree(root);    return 0;} |
Java
import java.util.*;Â
// Definition of TreeNode classclass TreeNode {    int val;    TreeNode left;    TreeNode right;    // Constructor for TreeNode    TreeNode(int x) {        val = x;        left = right = null;    }}Â
class GFG {      // Function to print the in-order traversal of a binary tree    public void printTree(TreeNode root) {        if (root == null) return;                 // Recursively print the left subtree        printTree(root.left);               System.out.print(root.val + " ");                 // Recursively print the right subtree        printTree(root.right);    }           // Recursive function to store the nodes in a map with level as key    public void dfsit(TreeNode rt, int key, Map<Integer, List<TreeNode>> mp) {        if (rt == null) return;        if (!mp.containsKey(key)) {            mp.put(key, new ArrayList<>());        }        mp.get(key).add(rt);        dfsit(rt.right, key + 1, mp);        dfsit(rt.left, key + 1, mp);        rt.left = null;        rt.right = null;    }Â
    public TreeNode shiftRight(TreeNode root) {        Map<Integer, List<TreeNode>> mp = new HashMap<>();        dfsit(root, 0, mp);Â
        TreeNode cur = new TreeNode(-1);        Queue<TreeNode> st = new LinkedList<>();        st.offer(cur);Â
        int i = 0;        int n = mp.size();        while (i < n) {               // Get the list of nodes for the current level            List<TreeNode> nd = mp.get(i);            int j = 0;            Queue<TreeNode> tmp = new LinkedList<>();            while (j < nd.size()) {                TreeNode r = st.poll();                  // Set the right child of the node to the current node in the list                r.right = nd.get(j);                tmp.offer(nd.get(j));                j++;                if (j < nd.size()) {                    r.left = nd.get(j);                    tmp.offer(nd.get(j));                    j++;                }            }            st = tmp;            i++;        }        return cur.right;    }           //Driver Code    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.left = new TreeNode(4);        root.left.right = new TreeNode(5);        root.right.right = new TreeNode(6);Â
        GFG solution = new GFG();        root = solution.shiftRight(root);Â
        solution.printTree(root);    }} |
Python3
# Python 3 program for the above approachfrom typing import Listfrom collections import dequeÂ
# Structure of a Tree nodeclass TreeNode:    def __init__(self, x: int) -> None:        self.val = x        self.left = None        self.right = NoneÂ
# Function to print Inorder Traversal of a Binary Treedef print_tree(root: TreeNode) -> None:    if not root:        return    # Traverse left child    print_tree(root.left)    # Print current node    print(root.val, end=" ")    # Traverse right child    print_tree(root.right)Â
def dfsit(rt: TreeNode, key: int, mp: List[List[TreeNode]]) -> None:    if not rt:        return    mp[key].append(rt)    dfsit(rt.right, key + 1, mp)    dfsit(rt.left, key + 1, mp)    rt.left = None    rt.right = NoneÂ
def shift_right(root: TreeNode) -> TreeNode:    tmp = root    mp = [[] for _ in range(10000)]    i = 0    dfsit(root, 0, mp)    n = len([lst for lst in mp if lst])    cur = TreeNode(-1)    st = deque([cur])    while i < n:        nd = mp[i]        j = 0        tmp = deque()        while j < len(nd):            r = st.popleft()            r.right = nd[j]            tmp.append(nd[j])            j += 1            if j < len(nd):                r.left = nd[j]                tmp.append(nd[j])                j += 1        st = tmp        i += 1    return cur.rightÂ
# Driver Coderoot = TreeNode(1)root.left = TreeNode(2)root.right = TreeNode(3)root.left.left = TreeNode(4)Â
root.left.right = TreeNode(5)root.right.right = TreeNode(6)Â
# Function Callroot = shift_right(root)Â
# Print the inOrder Traversalprint_tree(root)Â
# This code is contributed by Potta Lokesh |
C#
using System;using System.Collections.Generic;Â
// Definition of TreeNode classpublic class TreeNode {  public int val;  public TreeNode left;  public TreeNode right;     // Constructor for TreeNode  public TreeNode(int x)  {    val = x;    left = right = null;  }}Â
class GFG {     // Function to print the in-order traversal of a binary  // tree  public void PrintTree(TreeNode root)  {    if (root == null)      return;Â
    // Recursively print the left subtree    PrintTree(root.left);Â
    Console.Write(root.val + " ");Â
    // Recursively print the right subtree    PrintTree(root.right);  }Â
  // Recursive function to store the nodes in a map with  // level as key  public void dfsit(TreeNode rt, int key,                    Dictionary<int, List<TreeNode> > mp)  {    if (rt == null)      return;    if (!mp.ContainsKey(key)) {      mp.Add(key, new List<TreeNode>());    }    mp[key].Add(rt);    dfsit(rt.right, key + 1, mp);    dfsit(rt.left, key + 1, mp);    rt.left = null;    rt.right = null;  }Â
  public TreeNode ShiftRight(TreeNode root)  {    Dictionary<int, List<TreeNode> > mp      = new Dictionary<int, List<TreeNode> >();    dfsit(root, 0, mp);Â
    TreeNode cur = new TreeNode(-1);    Queue<TreeNode> st = new Queue<TreeNode>();    st.Enqueue(cur);Â
    int i = 0;    int n = mp.Count;    while (i < n) {      // Get the list of nodes for the current level      List<TreeNode> nd = mp[i];      int j = 0;      Queue<TreeNode> tmp = new Queue<TreeNode>();      while (j < nd.Count) {        TreeNode r = st.Dequeue();        // Set the right child of the node to the        // current node in the list        r.right = nd[j];        tmp.Enqueue(nd[j]);        j++;        if (j < nd.Count) {          r.left = nd[j];          tmp.Enqueue(nd[j]);          j++;        }      }      st = tmp;      i++;    }    return cur.right;  }Â
  // Driver Code  public static void Main()  {    TreeNode root = new TreeNode(1);    root.left = new TreeNode(2);    root.right = new TreeNode(3);    root.left.left = new TreeNode(4);    root.left.right = new TreeNode(5);    root.right.right = new TreeNode(6);Â
    GFG solution = new GFG();    root = solution.ShiftRight(root);Â
    solution.PrintTree(root);  }} |
Javascript
// Javascript program for the above approach// structure of a tree nodeclass TreeNode{Â Â Â Â constructor(x){Â Â Â Â Â Â Â Â this.val = x;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }}Â
// function to print norder // traversal of a binary treefunction printTree(root){    if(root == null)         return;    // traverse left child    printTree(root.left);         // print current node    console.log(root.val + " ");         // traverse the right child    printTree(root.right);}Â
function dfsit(rt, key, mp){Â Â Â Â if(rt == null) return;Â Â Â Â if(mp.has(key)){Â Â Â Â Â Â Â Â mp.get(key).push(rt);Â Â Â Â }else{Â Â Â Â Â Â Â Â mp.set(key, [rt]);Â Â Â Â }Â Â Â Â dfsit(rt.right, key+1, mp);Â Â Â Â dfsit(rt.left, key+1, mp);Â Â Â Â rt.left = null;Â Â Â Â rt.right = null;}Â
function shiftRight(root){Â Â Â Â let tmp = root;Â Â Â Â let mp = new Map();Â Â Â Â let i = 0;Â Â Â Â Â Â Â Â Â dfsit(root, 0, mp);Â Â Â Â let n = mp.size;Â Â Â Â let cur = new TreeNode(-1);Â Â Â Â Â Â Â Â Â let st = [];Â Â Â Â st.push(cur);Â Â Â Â Â Â Â Â Â while(i < n){Â Â Â Â Â Â Â Â let nd = mp.get(i);Â Â Â Â Â Â Â Â let j = 0;Â Â Â Â Â Â Â Â let tmp = [];Â Â Â Â Â Â Â Â while(j < nd.length){Â Â Â Â Â Â Â Â Â Â Â Â let r = st.shift();Â Â Â Â Â Â Â Â Â Â Â Â r.right = nd[j];Â Â Â Â Â Â Â Â Â Â Â Â tmp.push(nd[j]);Â Â Â Â Â Â Â Â Â Â Â Â j++;Â Â Â Â Â Â Â Â Â Â Â Â if(j<nd.length){Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â r.left = nd[j];Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â tmp.push(nd[j]);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â j++;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â st = tmp;Â Â Â Â Â Â Â Â i++;Â Â Â Â }Â Â Â Â return cur.right;}Â
// driver codelet root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);root.left.left = new TreeNode(4);root.left.right = new TreeNode(5);root.right.right = new TreeNode(6);Â
// function callroot = shiftRight(root);Â
//Â print the inorder traversalprintTree(root);Â
// This code is contributed by Yash Agarwal(yashagarwal2852002) |
2 4 1 5 3 6
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



