Skip to content

Commit 0ce63f0

Browse files
authored
Merge branch 'smv1999:master' into master
2 parents 39db948 + 21edf8c commit 0ce63f0

File tree

1 file changed

+129
-0
lines changed

1 file changed

+129
-0
lines changed
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
# https://practice.geeksforgeeks.org/problems/mirror-tree/1/
2+
3+
4+
5+
'''
6+
class Node:
7+
def _init_(self, val):
8+
self.right = None
9+
self.data = val
10+
self.left = None
11+
'''
12+
# your task is to complete this function
13+
14+
class Solution:
15+
#Function to convert a binary tree into its mirror tree.
16+
17+
18+
def mirror(self,root):
19+
20+
# Code here
21+
if(root == None):
22+
return
23+
else:
24+
temp = root
25+
self.mirror(root.left)
26+
self.mirror(root.right)
27+
temp = root.left
28+
root.left = root.right
29+
root.right = temp
30+
31+
return root
32+
33+
34+
35+
#{
36+
# Driver Code Starts
37+
#Initial Template for Python 3
38+
39+
from collections import deque
40+
# Tree Node
41+
class Node:
42+
def __init__(self, val):
43+
self.right = None
44+
self.data = val
45+
self.left = None
46+
47+
48+
def inorderTraversalUtil(root):
49+
# Code here
50+
if root is None:
51+
return
52+
inorderTraversalUtil(root.left)
53+
print(root.data, end=' ')
54+
inorderTraversalUtil(root.right)
55+
56+
def inorderTraversal(root):
57+
# Code here
58+
inorderTraversalUtil(root)
59+
print()
60+
61+
# Function to Build Tree
62+
def buildTree(s):
63+
#Corner Case
64+
if(len(s)==0 or s[0]=="N"):
65+
return None
66+
67+
# Creating list of strings from input
68+
# string after spliting by space
69+
ip=list(map(str,s.split()))
70+
71+
# Create the root of the tree
72+
root=Node(int(ip[0]))
73+
size=0
74+
q=deque()
75+
76+
# Push the root to the queue
77+
q.append(root)
78+
size=size+1
79+
80+
# Starting from the second element
81+
i=1
82+
while(size>0 and i<len(ip)):
83+
# Get and remove the front of the queue
84+
currNode=q[0]
85+
q.popleft()
86+
size=size-1
87+
88+
# Get the current node's value from the string
89+
currVal=ip[i]
90+
91+
# If the left child is not null
92+
if(currVal!="N"):
93+
94+
# Create the left child for the current node
95+
currNode.left=Node(int(currVal))
96+
97+
# Push it to the queue
98+
q.append(currNode.left)
99+
size=size+1
100+
# For the right child
101+
i=i+1
102+
if(i>=len(ip)):
103+
break
104+
currVal=ip[i]
105+
106+
# If the right child is not null
107+
if(currVal!="N"):
108+
109+
# Create the right child for the current node
110+
currNode.right=Node(int(currVal))
111+
112+
# Push it to the queue
113+
q.append(currNode.right)
114+
size=size+1
115+
i=i+1
116+
return root
117+
118+
119+
if __name__=="__main__":
120+
t=int(input())
121+
for _ in range(0,t):
122+
s=input()
123+
root=buildTree(s)
124+
Solution().mirror(root)
125+
inorderTraversal(root)
126+
127+
128+
129+
# } Driver Code Ends

0 commit comments

Comments
 (0)