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.

    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;
    cout << 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;    
        int L, R;
		cin >> swapLevel;
    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());
    public static void swapKDevisible(Node nd, int k){
    public static Node buildTree(Scanner sc){
        HashMap<Integer, Node> cache = new HashMap<Integer, Node>();
        Node root = new Node(null, null, 1, 1);
        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);
        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){
        Node t = nd.right;
        nd.right = nd.left;
        nd.left = t;
    public static void inOrderTraversal(Node nd){
        System.out.print(nd.data+" ");
    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){

In Pytho3 :

def inorder(T) :
    stack = [1]
    result = []
    while stack :
        i = stack.pop()
        if i > 0 :
            if T[i][1] > 0 : 
            if T[i][0] > 0 : 
        else :
    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 :
            if T[i][1] > 0 :
        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) :
    print(" ".join(str(_) for _ in inorder(T)))

In C :

#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){
		else {
			else if (level<k){
				int left = arr[i].left;
				int right = arr[i].right;
			else {


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){
		int left = arr[i].left;
		int right = arr[i].right;
		printf("%d ",i);

int main(){
	int i,n,t,k;
	struct node *arr = (struct node *)(malloc(sizeof(struct node) * (n+1)));
		arr[i].data = i;
	int j=1;
	int depth = cDepth(arr,1);
	while(t-->0) {
		//struct node *arrT = (struct node *)(malloc(sizeof(struct node) * (n+1)));	
		//copy original contents
			arrT[i].data = arr[i].data;
			arrT[i].left = arr[i].left;
			arrT[i].right = arr[i].right;
		int tempk = k;
			tempk = k * j;
        if(t!=0){ printf("\n"); }
		//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

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

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

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →