Skip to content

Instantly share code, notes, and snippets.

@nbarnold01
Created November 10, 2015 13:25
Show Gist options
  • Save nbarnold01/afc4ab8284dfdfa02b85 to your computer and use it in GitHub Desktop.
Save nbarnold01/afc4ab8284dfdfa02b85 to your computer and use it in GitHub Desktop.
//
// main.cpp
// Swap Nodes [Algo]
//
// Created by Nathan Arnold on 11/10/15.
// Copyright © 2015 Nathan Arnold. All rights reserved.
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue> // std::queue
using namespace std;
struct Node
{
int data;
struct Node *left;
struct Node *right;
};
void swapNodes(Node *root, int level, int swapLevel){
if (root) {
level += 1;
if (level % swapLevel == 0) {
// cout<<"Swapping at root: "<<root->data;
//
// if (root->left){
// cout<< " left: "<<root->left->data;
// }
//
// if (root->right){
// cout <<" right: "<<root->right->data;
//
// }
// cout<<"\n";
Node *temp = root->left;
root->left = root->right;
root->right = temp;
}
swapNodes(root->left, level, swapLevel);
swapNodes(root->right, level, swapLevel);
}
}
void Inorder(Node *root) {
if (root){
Inorder(root->left);
printf("%d ",root->data);
Inorder(root->right);
}
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int numberOfNodes = 0;
int result = scanf("%d",&numberOfNodes);
if (numberOfNodes){
queue<Node*> queue;
Node *first = new Node();
first->data = 1;
queue.push(first);
for (int i = 0; i < numberOfNodes; i++){
Node *root = queue.front();
queue.pop();
Node *node1 = new Node();
Node *node2 = new Node();
int val1 = 0;
int val2 = 0;
scanf("%d %d",&val1, &val2);
if (val1 > -1){
node1->data = val1;
root->left = node1;
queue.push(node1);
}
if (val2 > -1){
node2->data = val2;
root->right = node2;
queue.push(node2);
}
}
int numberOfSwaps = 0;
scanf("%d",&numberOfSwaps);
for (int i=0; i< numberOfSwaps; i++){
int swap = 0;
scanf("%d",&swap);
swapNodes(first, 0, swap);
Inorder(first);
cout<<"\n";
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment