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 :



title-img


                            Solution in C :

In   C :





#include <stdio.h>
#include <stdlib.h>

struct node
{
    int id;
    int depth;
    struct node *left, *right;
};

void
inorder(struct node* tree)
{
    if(tree == NULL)
        return;

    inorder(tree->left);
    printf("%d ",tree->id);
    inorder((tree->right));

}


int
main(void)
{
    int no_of_nodes, i = 0;
    int l,r, max_depth,k;
    struct node* temp = NULL;
    scanf("%d",&no_of_nodes);
    struct node* tree = (struct node *) calloc(no_of_nodes , sizeof(struct node));
    tree[0].depth = 1;
    while(i <  no_of_nodes )
    {
        tree[i].id = i+1;
        scanf("%d %d",&l,&r);
        if(l ==  -1)
            tree[i].left = NULL;
        else
             {
                 tree[i].left = &tree[l-1];
                 tree[i].left->depth = tree[i].depth + 1;
                 max_depth = tree[i].left->depth;
             }

         if(r ==  -1)
            tree[i].right = NULL;
        else
             {
                 tree[i].right = &tree[r-1];
                 tree[i].right->depth = tree[i].depth + 1;
                 max_depth = tree[i].right->depth+2;
             }

    i++;
    }

    scanf("%d", &i);
    while(i--)
    {
        scanf("%d",&l);
        r = l;
        while(l <= max_depth)
        {
            for(k = 0;k < no_of_nodes; ++k)
            {
                if(tree[k].depth == l)
                {
                    temp = tree[k].left;
                    tree[k].left = tree[k].right;
                    tree[k].right = temp;
                }
            }
            l = l + r;
        }
        inorder(tree);
        printf("\n");
    }



    return 0;
}
                        


                        Solution in C++ :

In  C ++ :




#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct Vertex {
    int left, right;
};

typedef vector<Vertex> Vertices;

void SwapNodes(Vertices &vs, int k, int root, int depth, bool &start) {
    if (depth % k == 0) {
        swap(vs[root].left, vs[root].right);
    }

    if (vs[root].left != -1) {
        SwapNodes(vs, k, vs[root].left, depth + 1, start);
    }

    if (start) {
        start = false;
    } else {
        cout << " ";
    }
    cout << root;

    if (vs[root].right != -1) {
        SwapNodes(vs, k, vs[root].right, depth + 1, start);
    }
}


int main() {
    size_t num_vertices;
    cin >> num_vertices;
    Vertices vertices(num_vertices + 1);
    for (size_t v = 0; v < num_vertices; ++v) {
        cin >> vertices[v + 1].left >> vertices[v + 1].right;
    }
    size_t num_tests;
    cin >> num_tests;
    for (size_t t = 0; t < num_tests; ++t) {
        int k;
        cin >> k;
        bool start = true;
        SwapNodes(vertices, k, 1, 1, start);
        cout << "\n";
    }
    return 0;
}
                    


                        Solution in Java :

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;
        }
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :







def printTree(tree):
        s = ''
        todo = [(1, True)]
        while todo:
                i, pl = todo.pop()
                a, b = tree[i]
                if pl:
                        todo.append((i, False))
                        if a != -1:
                                todo.append((a, True))
                else:
                        s += ' %d' % i
                        if b != -1:
                                todo.append((b, True))
        print(s[1:])

def swapNodes(tree, k):
        todo = [(1, 1)]
        while todo:
                i, d = todo.pop()
                a, b = tree[i]
                if d % k == 0:
                        tree[i] = b, a
                if a != -1:
                        todo.append((a, d+1))
                if b != -1:
                        todo.append((b, d+1))

n = int(input())
nodes = [None]
for _ in range(n):
        a, b = map(int, input().split())
        nodes.append((a, b))

t = int(input())
for _ in range(t):
        k = int(input())
        swapNodes(nodes, k)
        printTree(nodes)
                    


View More Similar Problems

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →