Given the root of a binary tree, reverse the values of nodes at every alternate level from left to right, while keeping the tree structure unchanged. Only the node values may be modified. The root node is considered to be at level 0. Therefore, values at levels 1, 3, 5, ... are reversed.
Examples:
Input: root[] = [1, 2, 3, 42, 51, 63, 72]
Output:
Explanation: Level 1 contains the nodes 2 and 3, so their values are swapped. Levels 0 and 2 remain unchanged.
Input: root[] = [1, 2, N, 3, 4, 5, N, N, 6]
Output:
Explanation: Level 1 contains only one node, so reversing it has no visible effect. At level 3, the node values are reversed from left to right. Levels 0 and 2 remain unchanged.
[Expected Approach 1] Level Order Traversal with Extra Value Array - O(n) Time O(n) Space
The idea is based on level-order traversal line by line. For every alternate level (1, 3, 5, ...), store the node values in a separate array, reverse the array, and then assign the reversed values back to the nodes of that level. The tree structure remains unchanged; only node values are modified.
C++
#include<algorithm>#include<iostream>#include<queue>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};voidalternateReverse(Node*root){// If tree is empty, nothing to reverseif(root==nullptr)return;queue<Node*>q;q.push(root);// Root is at level 0intlvl=0;// Perform level order traversalwhile(!q.empty()){intsz=q.size();// Stores nodes and values of current odd levelvector<Node*>nodes;vector<int>values;for(inti=0;i<sz;i++){Node*curr=q.front();q.pop();// Store nodes and values only for odd levelsif(lvl%2==1){nodes.push_back(curr);values.push_back(curr->data);}// Push left childif(curr->left)q.push(curr->left);// Push right childif(curr->right)q.push(curr->right);}// Reverse values at alternate levelsif(lvl%2==1){reverse(values.begin(),values.end());// Assign reversed values back to nodesfor(inti=0;i<nodes.size();i++){nodes[i]->data=values[i];}}lvl++;}}// Inorder traversal of treevoidinorder(Node*root){if(root==nullptr)return;inorder(root->left);cout<<root->data<<" ";inorder(root->right);}// Driver Codeintmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(42);root->left->right=newNode(51);root->right->left=newNode(63);root->right->right=newNode(72);alternateReverse(root);inorder(root);return0;}
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGfG{publicstaticvoidalternateReverse(Noderoot){// If tree is empty, nothing to reverseif(root==null)return;Queue<Node>q=newQueue<Node>();q.Enqueue(root);// Root is at level 0intlvl=0;// Perform level order traversalwhile(q.Count>0){intsz=q.Count;// Stores nodes and values of current odd levelList<Node>nodes=newList<Node>();List<int>values=newList<int>();for(inti=0;i<sz;i++){Nodecurr=q.Dequeue();// Store nodes and values only for odd// levelsif(lvl%2==1){nodes.Add(curr);values.Add(curr.data);}// Push left childif(curr.left!=null)q.Enqueue(curr.left);// Push right childif(curr.right!=null)q.Enqueue(curr.right);}// Reverse values at alternate levelsif(lvl%2==1){values.Reverse();// Assign reversed values back to nodesfor(inti=0;i<nodes.Count;i++){nodes[i].data=values[i];}}lvl++;}}// Inorder traversal of treepublicstaticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);Console.Write(root.data+" ");inorder(root.right);}// Driver CodepublicstaticvoidMain(string[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(42);root.left.right=newNode(51);root.right.left=newNode(63);root.right.right=newNode(72);alternateReverse(root);inorder(root);}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionalternateReverse(root){// If tree is empty, nothing to reverseif(root===null)return;letq=[];q.push(root);// Root is at level 0letlvl=0;// Perform level order traversalwhile(q.length>0){letsz=q.length;// Stores nodes and values of current odd levelletnodes=[];letvalues=[];for(leti=0;i<sz;i++){letcurr=q.shift();// Store nodes and values only for odd levelsif(lvl%2===1){nodes.push(curr);values.push(curr.data);}// Push left childif(curr.left!==null)q.push(curr.left);// Push right childif(curr.right!==null)q.push(curr.right);}// Reverse values at alternate levelsif(lvl%2===1){values.reverse();// Assign reversed values back to nodesfor(leti=0;i<nodes.length;i++){nodes[i].data=values[i];}}lvl++;}}// Inorder traversal of treefunctioninorder(root){if(root===null)return;inorder(root.left);console.log(root.data);inorder(root.right);}// Driver Codeletroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(42);root.left.right=newNode(51);root.right.left=newNode(63);root.right.right=newNode(72);alternateReverse(root);inorder(root);
Output
42 3 51 1 63 2 72
[Expected Approach 2] Level Order Traversal and Pointer Array - O(n) Time O(n) Space
The idea is same as above except the fact that we use pointer or reference array to store items of a level. In real world situations, the actual data maybe large, so this is a space optimized version for nodes having large data.
C++
#include<iostream>#include<queue>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};voidalternateReverse(Node*root){// If tree is empty, nothing to reverseif(!root)return;queue<Node*>q;q.push(root);// Root is considered at level 0intlvl=0;// Standard BFS traversalwhile(!q.empty()){intsz=q.size();// Stores all nodes present at current levelvector<Node*>cur;for(inti=0;i<sz;i++){Node*node=q.front();q.pop();cur.push_back(node);// Push left and right child for next level traversalif(node->left)q.push(node->left);if(node->right)q.push(node->right);}// Reverse node values at alternate levels// Here, levels 1, 3, 5 ... are reversedif(lvl%2==1){intl=0;intr=cur.size()-1;// Swap values from both endswhile(l<r){swap(cur[l]->data,cur[r]->data);l++;r--;}}lvl++;}}// Inorder traversal of treevoidinorder(Node*root){if(root==nullptr)return;inorder(root->left);cout<<root->data<<" ";inorder(root->right);}// Driver Codeintmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(42);root->left->right=newNode(51);root->right->left=newNode(63);root->right->right=newNode(72);alternateReverse(root);inorder(root);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.Stack;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGfG{publicstaticvoidalternateReverse(Noderoot){// If tree is empty, nothing to reverseif(root==null)return;Queue<Node>q=newLinkedList<>();q.add(root);// Root is considered at level 0intlvl=0;// Standard BFS traversalwhile(!q.isEmpty()){intsz=q.size();// Stores all nodes present at current levelStack<Node>cur=newStack<>();for(inti=0;i<sz;i++){Nodenode=q.poll();cur.push(node);// Push left and right child for next level// traversalif(node.left!=null)q.add(node.left);if(node.right!=null)q.add(node.right);}// Reverse node values at alternate levels// Here, levels 1, 3, 5... are reversedif(lvl%2==1){intl=0;intr=cur.size()-1;// Swap values from both endswhile(l<r){inttemp=cur.get(l).data;cur.get(l).data=cur.get(r).data;cur.get(r).data=temp;l++;r--;}}lvl++;}}// Inorder traversal of treepublicstaticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);System.out.print(root.data+" ");inorder(root.right);}// Driver Codepublicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(42);root.left.right=newNode(51);root.right.left=newNode(63);root.right.right=newNode(72);alternateReverse(root);inorder(root);}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefalternateReverse(root):# If tree is empty, nothing to reverseifnotroot:returnq=deque([root])# Root is considered at level 0lvl=0# Standard BFS traversalwhileq:sz=len(q)# Stores all nodes present at current levelcur=[]for_inrange(sz):node=q.popleft()cur.append(node)# Push left and right child for next level traversalifnode.left:q.append(node.left)ifnode.right:q.append(node.right)# Reverse node values at alternate levels# Here, levels 1, 3, 5... are reversediflvl%2==1:l,r=0,len(cur)-1# Swap values from both endswhilel<r:cur[l].data,cur[r].data=cur[r].data,cur[l].datal+=1r-=1lvl+=1# Inorder traversal of treedefinorder(root):ifrootisNone:returninorder(root.left)print(root.data,end=' ')inorder(root.right)# Driver Codeif__name__=='__main__':root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(42)root.left.right=Node(51)root.right.left=Node(63)root.right.right=Node(72)alternateReverse(root)inorder(root)
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGfG{publicstaticvoidalternateReverse(Noderoot){// If tree is empty, nothing to reverseif(root==null)return;Queue<Node>q=newQueue<Node>();q.Enqueue(root);// Root is considered at level 0intlvl=0;// Standard BFS traversalwhile(q.Count>0){intsz=q.Count;// Stores all nodes present at current levelList<Node>cur=newList<Node>();for(inti=0;i<sz;i++){Nodenode=q.Dequeue();cur.Add(node);// Push left and right child for next level// traversalif(node.left!=null)q.Enqueue(node.left);if(node.right!=null)q.Enqueue(node.right);}// Reverse node values at alternate levels// Here, levels 1, 3, 5... are reversedif(lvl%2==1){intl=0;intr=cur.Count-1;// Swap values from both endswhile(l<r){inttemp=cur[l].data;cur[l].data=cur[r].data;cur[r].data=temp;l++;r--;}}lvl++;}}// Inorder traversal of treepublicstaticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);Console.Write(root.data+" ");inorder(root.right);}// Driver CodepublicstaticvoidMain(){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(42);root.left.right=newNode(51);root.right.left=newNode(63);root.right.right=newNode(72);alternateReverse(root);inorder(root);}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionalternateReverse(root){// If tree is empty, nothing to reverseif(!root)return;letq=[];q.push(root);// Root is considered at level 0letlvl=0;// Standard BFS traversalwhile(q.length>0){letsz=q.length;// Stores all nodes present at current levelletcur=[];for(leti=0;i<sz;i++){letnode=q.shift();cur.push(node);// Push left and right child for next level// traversalif(node.left)q.push(node.left);if(node.right)q.push(node.right);}// Reverse node values at alternate levels// Here, levels 1, 3, 5... are reversedif(lvl%2==1){letl=0;letr=cur.length-1;// Swap values from both endswhile(l<r){[cur[l].data,cur[r].data]=[cur[r].data,cur[l].data];l++;r--;}}lvl++;}}// Inorder traversal of treefunctioninorder(root){if(root==null)return;inorder(root.left);console.log(root.data);inorder(root.right);}// Driver Codeletroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(42);root.left.right=newNode(51);root.right.left=newNode(63);root.right.right=newNode(72);alternateReverse(root);inorder(root);