We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classNode{public:intdata;Node*left;Node*right;Node(intx):data(x),left(nullptr),right(nullptr){}};voidinorder(Node*root,vector<int>&res_value){if(!root)return;inorder(root->left,res_value);res_value.push_back(root->data);inorder(root->right,res_value);}voidswapNodesUtil(Node*root,intlevel,intk){if(!root||(!root->left&&!root->right))return;if(level%k==0){swap(root->left,root->right);}swapNodesUtil(root->left,level+1,k);swapNodesUtil(root->right,level+1,k);}vector<vector<int>>swapNodes(vector<vector<int>>indexes,vector<int>queries){Node*root=newNode(1);//build tree from queuequeue<Node*>q;q.push(root);for(inti=0;i<indexes.size();i++){Node*cur=q.front();q.pop();cout<<cur->data<<endl;if(indexes[i][0]!=-1){cur->left=newNode(indexes[i][0]);q.push(cur->left);}if(indexes[i][1]!=-1){cur->right=newNode(indexes[i][1]);q.push(cur->right);}}// swap node and travelsal to save tree to arrayvector<vector<int>>res;for(inti=0;i<queries.size();i++){vector<int>res_value;swapNodesUtil(root,1,queries[i]);inorder(root,res_value);res.push_back(res_value);}returnres;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Swap Nodes [Algo]
You are viewing a single comment's thread. Return to all comments →
C++