Swap Nodes [Algo]
Problem Statement :
A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from the left child of the root node and keep exploring the left subtree until you reach a leaf. When you reach a leaf, back up to its parent, check for a right child and visit it if there is one. If there is not a child, you've explored its left and right subtrees fully. If there is a right child, traverse its left subtree then its right in the same manner. Keep doing this until you have traversed the entire tree. You will only store the values of a node as you visit when one of the following is true: it is the first node visited, the first time visited it is a leaf, should only be visited once all of its subtrees have been explored, should only be visited once while this is true it is the root of the tree, the first time visited Swapping: Swapping subtrees of a node means that if initially node has left subtree L and right subtree R, then after swapping, the left subtree will be R and the right subtree, L. For example, in the following tree, we swap children of node 1. Depth 1 1 [1] / \ / \ 2 3 -> 3 2 [2] \ \ \ \ 4 5 5 4 [3] In-order traversal of left tree is 2 4 1 3 5 and of right tree is 3 5 1 2 4. Swap operation: We define depth of a node as follows: The root node is at depth 1. If the depth of the parent node is d, then the depth of current node will be d+1. Given a tree and an integer, k, in one operation, we need to swap the subtrees of all the nodes at each depth h, where h ∈ [k, 2k, 3k,...]. In other words, if h is a multiple of k, swap the left and right subtrees of that level. You are given a tree of n nodes where nodes are indexed from [1..n] and it is rooted at 1. You have to perform t swap operations on it, and after each swap operation print the in-order traversal of the current state of the tree. Function Description Complete the swapNodes function in the editor below. It should return a two-dimensional array where each element is an array of integers representing the node indices of an in-order traversal after a swap operation. swapNodes has the following parameter(s): - indexes: an array of integers representing index values of each node[i] , beginning with node[1], the first element, as the root. - queries: an array of integers, each representing a k value. Input Format The first line contains n, number of nodes in the tree. Each of the next n lines contains two integers, a b, where a is the index of left child, and b is the index of right child of ith node. Note: -1 is used to represent a null node. The next line contains an integer, t, the size of queries. Each of the next t lines contains an integer queries[i], each being a value k. Output Format For each k, perform the swap operation and store the indices of your in-order traversal to your result array. After all swap operations have been performed, return your result array for printing.
Solution :
Solution in C :
In C ++ :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> leftNode, rightNode;
int swapLevel;
void traverse(int node=1){
if (node == -1) return;
traverse(leftNode[node]);
cout << node << " ";
traverse(rightNode[node]);
if (node == 1) cout << endl;
}
void swap(int level=1, int node=1) {
if (node == -1) return;
if (level % swapLevel == 0) {
int tmp = leftNode[node];
leftNode[node] = rightNode[node];
rightNode[node] = tmp;
}
swap(level+1, leftNode[node]);
swap(level+1, rightNode[node]);
}
int main() {
int count;
cin>>count;
leftNode.push_back(0);
rightNode.push_back(0);
while(count--){
int L, R;
cin>>L>>R;
leftNode.push_back(L);
rightNode.push_back(R);
}
cin>>count;
while(count--){
cin >> swapLevel;
swap();
traverse();
}
return 0;
}
In Java :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
Node root = buildTree(in);
int t = in.nextInt();
for(int i=0;i<t;++i){
swapKDevisible(root, in.nextInt());
inOrderTraversal(root);
System.out.println();
}
}
public static void swapKDevisible(Node nd, int k){
if(nd==null)
return;
if(nd.depth%k==0){
swapChildren(nd);
}
swapKDevisible(nd.left,k);
swapKDevisible(nd.right,k);
}
public static Node buildTree(Scanner sc){
HashMap<Integer, Node> cache = new HashMap<Integer, Node>();
Node root = new Node(null, null, 1, 1);
cache.put(1,root);
int len = sc.nextInt();
for(int i=0;i<len;++i){
int ind1 = sc.nextInt();
int ind2 = sc.nextInt();
Node parent = cache.get(i+1);
Node left = buildNewNode(ind1,parent.depth+1);
Node right = buildNewNode(ind2,parent.depth+1);
if(ind1!=-1)
cache.put(ind1,left);
if(ind2!=-1)
cache.put(ind2,right);
parent.left=left;
parent.right=right;
}
return root;
}
public static Node buildNewNode(int data,int depth) {
if(data==-1) return null;
return new Node(null,null,data,depth);
}
public static void swapChildren(Node nd){
if(nd==null)
return;
Node t = nd.right;
nd.right = nd.left;
nd.left = t;
}
public static void inOrderTraversal(Node nd){
if(nd==null)
return;
inOrderTraversal(nd.left);
System.out.print(nd.data+" ");
inOrderTraversal(nd.right);
}
public static class Node{
public Node left;
public Node right;
public int data;
public int depth;
public Node(Node left, Node right, int data, int depth){
this.left=left;
this.right=right;
this.data=data;
this.depth=depth;
}
}
}
In Pytho3 :
def inorder(T) :
stack = [1]
result = []
while stack :
i = stack.pop()
if i > 0 :
if T[i][1] > 0 :
stack.append(T[i][1])
stack.append(-i)
if T[i][0] > 0 :
stack.append(T[i][0])
else :
result.append(-i)
return result
def swap(T, K) :
toVisit, depth = [1], 1
while toVisit :
if depth % K == 0 :
for i in toVisit :
T[i] = (T[i][1], T[i][0])
toVisit_ = []
for i in toVisit :
if T[i][0] > 0 :
toVisit_.append(T[i][0])
if T[i][1] > 0 :
toVisit_.append(T[i][1])
toVisit = toVisit_
depth += 1
N = int(input())
T = [None] + [tuple(int(_) for _ in input().split()) for _ in range(N)]
N = int(input())
for _ in range(N) :
swap(T,int(input()))
print(" ".join(str(_) for _ in inorder(T)))
In C :
#include<stdio.h>
#include<stdlib.h>
#define S(a) scanf("%d",&a)
#define SS(a,b) scanf("%d%d",&a,&b)
struct node {
int data;
int left;
int right;
};
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
void swapNodes(struct node *arr,int i,int level,int k){
if(i==-1){
return;
}
else {
if(level==k){
swap(&arr[i].left,&arr[i].right);
return;
}
else if (level<k){
int left = arr[i].left;
int right = arr[i].right;
level++;
swapNodes(arr,left,level,k);
swapNodes(arr,right,level,k);
return;
}
else {
return;
}
}
}
int cDepth(struct node *arr,int i){
if(i == -1){
return 0;
}
int left = arr[i].left;
int right = arr[i].right;
int l = cDepth(arr,left);
int r = cDepth(arr,right);
if(l>r) { return l+1;}
else { return r+1;}
}
void inorderTr(struct node *arr,int i){
if(i==-1){
return;
}
else{
int left = arr[i].left;
int right = arr[i].right;
inorderTr(arr,left);
printf("%d ",i);
inorderTr(arr,right);
}
}
int main(){
int i,n,t,k;
S(n);
struct node *arr = (struct node *)(malloc(sizeof(struct node) * (n+1)));
for(i=1;i<=n;i++){
arr[i].data = i;
SS(arr[i].left,arr[i].right);
}
S(t);
int j=1;
int depth = cDepth(arr,1);
while(t-->0) {
S(k);
j=1;
//struct node *arrT = (struct node *)(malloc(sizeof(struct node) * (n+1)));
//copy original contents
/*for(i=1;i<=n;i++){
arrT[i].data = arr[i].data;
arrT[i].left = arr[i].left;
arrT[i].right = arr[i].right;
}*/
int tempk = k;
while(tempk<=depth){
swapNodes(arr,1,1,tempk);
j++;
tempk = k * j;
}
inorderTr(arr,1);
if(t!=0){ printf("\n"); }
//free(arrT);
}
free(arr);
//for(i=1;i<=n;i++){
//arr[i].data = i+1;
// printf("%d\t%d\t%d\n",arr[i].data,arr[i].left,arr[i].right);
//}
return 0;
}
View More Similar Problems
Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →Delete a Node
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo
View Solution →