-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch-Swap Nodes [Algo].py
109 lines (91 loc) · 2.85 KB
/
Search-Swap Nodes [Algo].py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#Problem Link : https://www.hackerrank.com/challenges/swap-nodes-algo/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=search
#Ans:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'swapNodes' function below.
#
# The function is expected to return a 2D_INTEGER_ARRAY.
# The function accepts following parameters:
# 1. 2D_INTEGER_ARRAY indexes
# 2. INTEGER_ARRAY queries
#
def swapNodes(indexes, queries):
#
# Write your code here.
#
#modifying the recursion limit in python because of #10 and #11
sys.setrecursionlimit(1500)
#tree node
class Node:
def __init__(self, data, level):
self.data = data
self.left = None
self.right = None
self.level = level
#traverse the tree in order
def traverse_inorder(tree):
if tree.left:
traverse_inorder(tree.left)
item.append(tree.data)
if tree.right:
traverse_inorder(tree.right)
#building the tree
def create_tree(indexes):
from queue import Queue
#using queue to create the tree: BFS
q = Queue()
root = Node(1, 1)
maxlevel = 1
q.put(root)
for left, right in indexes:
cur = q.get()
if left != -1:
leftNode = Node(left, cur.level + 1)
cur.left = leftNode
q.put(leftNode)
if right != -1:
rightNode = Node(right, cur.level + 1)
cur.right = rightNode
q.put(rightNode)
#Finally the q is empty, and cur is at lowest level. Because there are always [-1, -1]s at the end of the indexes
maxlevel = cur.level
return (root, maxlevel)
#swaping respectively
def swap_tree(tree, ks):
if tree.left:
swap_tree(tree.left, ks)
if tree.right:
swap_tree(tree.right, ks)
if tree.level in ks:
tree.left, tree.right = tree.right, tree.left
return tree
tree, maxlevel = create_tree(indexes)
ret = []
for k in queries:
item = []
#list comprehensions
ks = [x for x in range(1, maxlevel+1) if x%k==0]
root = swap_tree(tree, ks)
traverse_inorder(root)
ret.append(item)
return ret
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
indexes = []
for _ in range(n):
indexes.append(list(map(int, input().rstrip().split())))
queries_count = int(input())
queries = []
for _ in range(queries_count):
queries_item = int(input())
queries.append(queries_item)
result = swapNodes(indexes, queries)
fptr.write('\n'.join([' '.join(map(str, x)) for x in result]))
fptr.write('\n')
fptr.close()