diff --git a/data_structures/binary_trees/Convert a Binary Tree into its Mirror Tree.py b/data_structures/binary_trees/Convert a Binary Tree into its Mirror Tree.py new file mode 100644 index 00000000..4c4085f9 --- /dev/null +++ b/data_structures/binary_trees/Convert a Binary Tree into its Mirror Tree.py @@ -0,0 +1,81 @@ +# Python3 program to convert a binary +# tree to its mirror + +# Utility function to create a new +# tree node +class newNode: + def __init__(self,data): + self.data = data + self.left = self.right = None + +""" Change a tree so that the roles of the + left and right pointers are swapped at + every node. + +So the tree... + 4 + / \ + 2 5 + / \ + 1 3 + +is changed to... + 4 + / \ + 5 2 + / \ + 3 1 +""" +def mirror(node): + + if (node == None): + return + else: + + temp = node + + """ do the subtrees """ + mirror(node.left) + mirror(node.right) + + """ swap the pointers in this node """ + temp = node.left + node.left = node.right + node.right = temp + +""" Helper function to print Inorder traversal.""" +def inOrder(node) : + + if (node == None): + return + + inOrder(node.left) + print(node.data, end = " ") + inOrder(node.right) + +# Driver code +if __name__ =="__main__": + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + + """ Print inorder traversal of + the input tree """ + print("Inorder traversal of the", + "constructed tree is") + inOrder(root) + + """ Convert tree to its mirror """ + mirror(root) + + """ Print inorder traversal of + the mirror tree """ + print("\nInorder traversal of", + "the mirror treeis ") + inOrder(root) + +# This code is contributed by +# Shubham Singh(SHUBHAMSINGH10) diff --git a/data_structures/linked_list/middle_element.py b/data_structures/linked_list/middle_element.py new file mode 100644 index 00000000..07bd1ef0 --- /dev/null +++ b/data_structures/linked_list/middle_element.py @@ -0,0 +1,37 @@ +class Node: + + # Function to initialise the node object + def __init__(self, data): + self.data = data + self.next = None + +class LinkedList: + + def __init__(self): + self.head = None + + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + # Function to get the middle of + # the linked list + def printMiddle(self): + slow_ptr = self.head + fast_ptr = self.head + + if self.head is not None: + while (fast_ptr is not None and fast_ptr.next is not None): + fast_ptr = fast_ptr.next.next + slow_ptr = slow_ptr.next + print("The middle element is: ", slow_ptr.data) + +# Driver code +list1 = LinkedList() +list1.push(5) +list1.push(4) +list1.push(2) +list1.push(3) +list1.push(1) +list1.printMiddle()