text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Sum of dependencies in a graph | To add an edge ; Find the sum of all dependencies ; Just find the size at each vector 's index ; Driver code
def addEdge ( adj , u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE DEDENT def findSum ( adj , V ) : NEW_LINE INDENT sum = 0 NEW_LINE for u in range ( V ) : NEW_LINE INDENT sum += len ( adj [ u ] ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 4 NEW_LINE adj = [ [ ] for i in range ( V ) ] NEW_LINE addEdge ( adj , 0 , 2 ) NEW_LINE addEdge ( adj , 0 , 3 ) NEW_LINE addEdge ( adj , 1 , 3 ) NEW_LINE addEdge ( adj , 2 , 3 ) NEW_LINE print ( " Sum ▁ of ▁ dependencies ▁ is " , findSum ( adj , V ) ) NEW_LINE DEDENT
Linked List | Set 2 ( Inserting a node ) | This function is in LinkedList class Function to insert a new node at the beginning ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node
def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = self . head NEW_LINE self . head = new_node NEW_LINE DEDENT
Linked List | Set 2 ( Inserting a node ) | This function is in LinkedList class . Inserts a new node after the given prev_node . This method is defined inside LinkedList class shown above ; 1. check if the given prev_node exists ; 2. Create new node & 3. Put in the data ; 4. Make next of new Node as next of prev_node ; 5. make next of prev_node as new_node
def insertAfter ( self , prev_node , new_data ) : NEW_LINE INDENT if prev_node is None : NEW_LINE INDENT print " The ▁ given ▁ previous ▁ node ▁ must ▁ inLinkedList . " NEW_LINE return NEW_LINE DEDENT new_node = Node ( new_data ) NEW_LINE new_node . next = prev_node . next NEW_LINE prev_node . next = new_node NEW_LINE DEDENT
Iterative Preorder Traversal | A binary tree node ; An iterative process to print preorder traveral of BT ; Base CAse ; create an empty stack and push root to it ; Pop all items one by one . Do following for every popped item a ) print it b ) push its right child c ) push its left child Note that right child is pushed first so that left is processed first ; Pop the top item from stack and print it ; Push right and left children of the popped node to stack ; Driver program to test above function
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def iterativePreorder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT nodeStack = [ ] NEW_LINE nodeStack . append ( root ) NEW_LINE while ( len ( nodeStack ) > 0 ) : NEW_LINE INDENT node = nodeStack . pop ( ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE if node . right is not None : NEW_LINE INDENT nodeStack . append ( node . right ) NEW_LINE DEDENT if node . left is not None : NEW_LINE INDENT nodeStack . append ( node . left ) NEW_LINE DEDENT DEDENT DEDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 2 ) NEW_LINE root . left . left = Node ( 3 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 2 ) NEW_LINE iterativePreorder ( root ) NEW_LINE
Find Length of a Linked List ( Iterative and Recursive ) | Node class ; Linked List class contains a Node object ; Function to initialize head ; This function is in LinkedList class . It inserts a new node at the beginning of Linked List . ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; This function counts number of nodes in Linked List recursively , given ' node ' as starting node . ; Base case ; Count is this node plus rest of the list ; A wrapper over getCountRec ( ) ; Code execution starts here ; Start with the empty list
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = self . head NEW_LINE self . head = new_node NEW_LINE DEDENT def getCountRec ( self , node ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + self . getCountRec ( node . next ) NEW_LINE DEDENT DEDENT def getCount ( self ) : NEW_LINE INDENT return self . getCountRec ( self . head ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT llist = LinkedList ( ) NEW_LINE llist . push ( 1 ) NEW_LINE llist . push ( 3 ) NEW_LINE llist . push ( 1 ) NEW_LINE llist . push ( 2 ) NEW_LINE llist . push ( 1 ) NEW_LINE print ' Count ▁ of ▁ nodes ▁ is ▁ : ' , llist . getCount ( ) NEW_LINE DEDENT
Iterative Preorder Traversal | Tree Node ; Iterative function to do Preorder traversal of the tree ; start from root node ( set current node to root node ) ; run till stack is not empty or current is not NULL ; Print left children while exist and keep appending right into the stack . ; We reach when curr is NULL , so We take out a right child from stack ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , data = 0 ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def preorderIterative ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT st = [ ] NEW_LINE curr = root NEW_LINE while ( len ( st ) or curr != None ) : NEW_LINE INDENT while ( curr != None ) : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE if ( curr . right != None ) : NEW_LINE INDENT st . append ( curr . right ) NEW_LINE DEDENT curr = curr . left NEW_LINE DEDENT if ( len ( st ) > 0 ) : NEW_LINE INDENT curr = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE DEDENT DEDENT DEDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 20 ) NEW_LINE root . right = Node ( 30 ) NEW_LINE root . left . left = Node ( 40 ) NEW_LINE root . left . left . left = Node ( 70 ) NEW_LINE root . left . right = Node ( 50 ) NEW_LINE root . right . left = Node ( 60 ) NEW_LINE root . left . left . right = Node ( 80 ) NEW_LINE preorderIterative ( root ) NEW_LINE
Write a function that counts the number of times a given int occurs in a Linked List | Counts the no . of occurrences of a node ( search_for ) in a linked list ( head )
def count ( self , temp , key ) : NEW_LINE INDENT if temp is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if temp . data == key : NEW_LINE INDENT return 1 + count ( temp . next , key ) NEW_LINE DEDENT return count ( temp . next , key ) NEW_LINE DEDENT
Detect loop in a linked list | Link list node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Returns true if there is a loop in linked list else returns false . ; If this node is already traverse it means there is a cycle ( Because you we encountering the node for the second time ) . ; If we are seeing the node for the first time , mark its flag as 1 ; Driver program to test above function ; Start with the empty list ; Create a loop for testing
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE self . flag = 0 NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) ; NEW_LINE new_node . data = new_data ; NEW_LINE new_node . flag = 0 ; NEW_LINE new_node . next = ( head_ref ) ; NEW_LINE ( head_ref ) = new_node ; NEW_LINE return head_ref NEW_LINE DEDENT def detectLoop ( h ) : NEW_LINE INDENT while ( h != None ) : NEW_LINE INDENT if ( h . flag == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT h . flag = 1 ; NEW_LINE h = h . next ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None ; NEW_LINE head = push ( head , 20 ) ; NEW_LINE head = push ( head , 4 ) ; NEW_LINE head = push ( head , 15 ) ; NEW_LINE head = push ( head , 10 ) NEW_LINE head . next . next . next . next = head ; NEW_LINE if ( detectLoop ( head ) ) : NEW_LINE INDENT print ( " Loop ▁ found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ Loop " ) NEW_LINE DEDENT DEDENT
Detect loop in a linked list | Python3 program to return first node of loop A binary tree node has data , pointer to left child and a pointer to right child Helper function that allocates a new node with the given data and None left and right pointers ; A utility function to pra linked list ; Function to detect first node of loop in a linked list that may contain loop ; Create a temporary node ; This condition is for the case when there is no loop ; Check if next is already pointing to temp ; Store the pointer to the next node in order to get to it in the next step ; Make next poto temp ; Get to the next node in the list ; Driver Code ; Create a loop for testing ( 5 is pointing to 3 )
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . key , end = " ▁ " ) NEW_LINE head = head . next NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def detectLoop ( head ) : NEW_LINE INDENT temp = " " NEW_LINE while ( head != None ) : NEW_LINE INDENT if ( head . next == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( head . next == temp ) : NEW_LINE INDENT return True NEW_LINE DEDENT nex = head . next NEW_LINE head . next = temp NEW_LINE head = nex NEW_LINE DEDENT return False NEW_LINE DEDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next = newNode ( 5 ) NEW_LINE head . next . next . next . next . next = head . next . next NEW_LINE found = detectLoop ( head ) NEW_LINE if ( found ) : NEW_LINE INDENT print ( " Loop ▁ Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ Loop " ) NEW_LINE DEDENT
Function to check if a singly linked list is palindrome | Node class ; Function to initialize head ; Function to check if given linked list is pallindrome or not ; To handle odd size list ; Initialize result ; Get the middle of the list . Move slow_ptr by 1 and fast_ptrr by 2 , slow_ptr will have the middle node ; We need previous of the slow_ptr for linked lists with odd elements ; fast_ptr would become NULL when there are even elements in the list and not NULL for odd elements . We need to skip the middle node for odd case and store it somewhere so that we can restore the original list ; Now reverse the second half and compare it with first half ; NULL terminate first half ; Reverse the second half ; Compare ; Reverse the second half again ; If there was a mid node ( odd size case ) which was not part of either first half or second half . ; Function to reverse the linked list Note that this function may change the head ; Function to check if two input lists have same data ; Both are empty return 1 ; Will reach here when one is NULL and other is not ; Function to insert a new node at the beginning ; Allocate the Node & Put in the data ; Link the old list off the new one ; Move the head to point to new Node ; A utility function to print a given linked list ; Driver code ; Start with the empty list
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def isPalindrome ( self , head ) : NEW_LINE INDENT slow_ptr = head NEW_LINE fast_ptr = head NEW_LINE prev_of_slow_ptr = head NEW_LINE midnode = None NEW_LINE res = True NEW_LINE if ( head != None and head . next != None ) : NEW_LINE INDENT while ( fast_ptr != None and fast_ptr . next != None ) : NEW_LINE INDENT fast_ptr = fast_ptr . next . next NEW_LINE prev_of_slow_ptr = slow_ptr NEW_LINE slow_ptr = slow_ptr . next NEW_LINE DEDENT if ( fast_ptr != None ) : NEW_LINE INDENT midnode = slow_ptr NEW_LINE slow_ptr = slow_ptr . next NEW_LINE DEDENT second_half = slow_ptr NEW_LINE prev_of_slow_ptr . next = None NEW_LINE second_half = self . reverse ( second_half ) NEW_LINE res = self . compareLists ( head , second_half ) NEW_LINE second_half = self . reverse ( second_half ) NEW_LINE if ( midnode != None ) : NEW_LINE INDENT prev_of_slow_ptr . next = midnode NEW_LINE midnode . next = second_half NEW_LINE DEDENT else : NEW_LINE INDENT prev_of_slow_ptr . next = second_half NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def reverse ( self , second_half ) : NEW_LINE INDENT prev = None NEW_LINE current = second_half NEW_LINE next = None NEW_LINE while current != None : NEW_LINE INDENT next = current . next NEW_LINE current . next = prev NEW_LINE prev = current NEW_LINE current = next NEW_LINE DEDENT second_half = prev NEW_LINE return second_half NEW_LINE DEDENT def compareLists ( self , head1 , head2 ) : NEW_LINE INDENT temp1 = head1 NEW_LINE temp2 = head2 NEW_LINE while ( temp1 and temp2 ) : NEW_LINE INDENT if ( temp1 . data == temp2 . data ) : NEW_LINE INDENT temp1 = temp1 . next NEW_LINE temp2 = temp2 . next NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( temp1 == None and temp2 == None ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = self . head NEW_LINE self . head = new_node NEW_LINE DEDENT def printList ( self ) : NEW_LINE INDENT temp = self . head NEW_LINE while ( temp ) : NEW_LINE INDENT print ( temp . data , end = " - > " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( " NULL " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = LinkedList ( ) NEW_LINE s = [ ' a ' , ' b ' , ' a ' , ' c ' , ' a ' , ' b ' , ' a ' ] NEW_LINE for i in range ( 7 ) : NEW_LINE INDENT l . push ( s [ i ] ) NEW_LINE l . printList ( ) NEW_LINE if ( l . isPalindrome ( l . head ) != False ) : NEW_LINE INDENT print ( " Is Palindrome " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not Palindrome " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT
Swap nodes in a linked list without swapping data | Python program to swap two given nodes of a linked list ; head of list ; Function to swap Nodes x and y in linked list by changing links ; Nothing to do if x and y are same ; Search for x ( keep track of prevX and CurrX ) ; Search for y ( keep track of prevY and currY ) ; If either x or y is not present , nothing to do ; If x is not head of linked list ; make y the new head ; If y is not head of linked list ; make x the new head ; Swap next pointers ; Function to add Node at beginning of list . ; 1. alloc the Node and put the data ; 2. Make next of new Node as head ; 3. Move the head to point to new Node ; This function prints contents of linked list starting from the given Node ; Driver program to test above function ; The constructed linked list is : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
class LinkedList ( object ) : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT class Node ( object ) : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def swapNodes ( self , x , y ) : NEW_LINE INDENT if x == y : NEW_LINE INDENT return NEW_LINE DEDENT prevX = None NEW_LINE currX = self . head NEW_LINE while currX != None and currX . data != x : NEW_LINE INDENT prevX = currX NEW_LINE currX = currX . next NEW_LINE DEDENT prevY = None NEW_LINE currY = self . head NEW_LINE while currY != None and currY . data != y : NEW_LINE INDENT prevY = currY NEW_LINE currY = currY . next NEW_LINE DEDENT if currX == None or currY == None : NEW_LINE INDENT return NEW_LINE DEDENT if prevX != None : NEW_LINE INDENT prevX . next = currY NEW_LINE DEDENT else : NEW_LINE INDENT self . head = currY NEW_LINE DEDENT if prevY != None : NEW_LINE INDENT prevY . next = currX NEW_LINE DEDENT else : NEW_LINE INDENT self . head = currX NEW_LINE DEDENT temp = currX . next NEW_LINE currX . next = currY . next NEW_LINE currY . next = temp NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_Node = self . Node ( new_data ) NEW_LINE new_Node . next = self . head NEW_LINE self . head = new_Node NEW_LINE DEDENT def printList ( self ) : NEW_LINE INDENT tNode = self . head NEW_LINE while tNode != None : NEW_LINE INDENT print tNode . data , NEW_LINE tNode = tNode . next NEW_LINE DEDENT DEDENT DEDENT llist = LinkedList ( ) NEW_LINE llist . push ( 7 ) NEW_LINE llist . push ( 6 ) NEW_LINE llist . push ( 5 ) NEW_LINE llist . push ( 4 ) NEW_LINE llist . push ( 3 ) NEW_LINE llist . push ( 2 ) NEW_LINE llist . push ( 1 ) NEW_LINE print " Linked ▁ list ▁ before ▁ calling ▁ swapNodes ( ) ▁ " NEW_LINE llist . printList ( ) NEW_LINE llist . swapNodes ( 4 , 3 ) NEW_LINE print " NEW_LINE Linked list after calling swapNodes ( ) " NEW_LINE llist . printList ( ) NEW_LINE
Postorder traversal of Binary Tree without recursion and without stack | A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Visited left subtree ; Visited right subtree ; Print node ; Driver program to test above functions
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def postorder ( head ) : NEW_LINE INDENT temp = head NEW_LINE visited = set ( ) NEW_LINE while ( temp and temp not in visited ) : NEW_LINE INDENT if ( temp . left and temp . left not in visited ) : NEW_LINE INDENT temp = temp . left NEW_LINE DEDENT elif ( temp . right and temp . right not in visited ) : NEW_LINE INDENT temp = temp . right NEW_LINE DEDENT else : NEW_LINE INDENT print ( temp . data , end = " ▁ " ) NEW_LINE visited . add ( temp ) NEW_LINE temp = head NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 8 ) NEW_LINE root . left = newNode ( 3 ) NEW_LINE root . right = newNode ( 10 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 4 ) NEW_LINE root . left . right . right = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 14 ) NEW_LINE root . right . right . left = newNode ( 13 ) NEW_LINE postorder ( root ) NEW_LINE DEDENT
Postorder traversal of Binary Tree without recursion and without stack | A Binary Tree Node Utility function to create a new tree node ; Visited left subtree ; Visited right subtree ; Print node ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . visited = False NEW_LINE DEDENT DEDENT def postorder ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp and temp . visited == False ) : NEW_LINE INDENT if ( temp . left and temp . left . visited == False ) : NEW_LINE INDENT temp = temp . left NEW_LINE DEDENT elif ( temp . right and temp . right . visited == False ) : NEW_LINE INDENT temp = temp . right NEW_LINE DEDENT else : NEW_LINE INDENT print ( temp . data , end = " ▁ " ) NEW_LINE temp . visited = True NEW_LINE temp = head NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 8 ) NEW_LINE root . left = newNode ( 3 ) NEW_LINE root . right = newNode ( 10 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 4 ) NEW_LINE root . left . right . right = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 14 ) NEW_LINE root . right . right . left = newNode ( 13 ) NEW_LINE postorder ( root ) NEW_LINE DEDENT
Josephus Circle implementation using STL list | structure for a node in circular linked list ; Function to find the only person left after one in every m - th node is killed in a circle of n nodes ; Create a circular linked list of size N . ; Connect last node to first ; while only one node is left in the linked list ; Find m - th node ; Remove the m - th node ; Driver program to test above functions
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def getJosephusPosition ( m , n ) : NEW_LINE INDENT head = Node ( 1 ) NEW_LINE prev = head NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT prev . next = Node ( i ) NEW_LINE prev = prev . next NEW_LINE prev . next = head NEW_LINE DEDENT ptr1 = head NEW_LINE ptr2 = head NEW_LINE while ( ptr1 . next != ptr1 ) : NEW_LINE INDENT count = 1 NEW_LINE while ( count != m ) : NEW_LINE INDENT ptr2 = ptr1 NEW_LINE ptr1 = ptr1 . next NEW_LINE count += 1 NEW_LINE DEDENT ptr2 . next = ptr1 . next NEW_LINE ptr1 = ptr2 . next NEW_LINE DEDENT print ( " Last ▁ person ▁ left ▁ standing ▁ ( Josephus ▁ Position ) ▁ is ▁ " , ptr1 . data ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 14 NEW_LINE m = 2 NEW_LINE getJosephusPosition ( m , n ) NEW_LINE DEDENT
Diagonal Traversal of Binary Tree | A binary tree node ; root - root of the binary tree d - distance of current line from rightmost - topmost slope . diagonalPrint - multimap to store Diagonal elements ( Passed by Reference ) ; Base Case ; Store all nodes of same line together as a vector ; Increase the vertical distance if left child ; Vertical distance remains same for right child ; Print diagonal traversal of given binary tree ; Create a dict to store diagnoal elements ; Driver Program
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def diagonalPrintUtil ( root , d , diagonalPrintMap ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT try : NEW_LINE INDENT diagonalPrintMap [ d ] . append ( root . data ) NEW_LINE DEDENT except KeyError : NEW_LINE INDENT diagonalPrintMap [ d ] = [ root . data ] NEW_LINE DEDENT diagonalPrintUtil ( root . left , d + 1 , diagonalPrintMap ) NEW_LINE diagonalPrintUtil ( root . right , d , diagonalPrintMap ) NEW_LINE DEDENT def diagonalPrint ( root ) : NEW_LINE INDENT diagonalPrintMap = dict ( ) NEW_LINE diagonalPrintUtil ( root , 0 , diagonalPrintMap ) NEW_LINE print " Diagonal ▁ Traversal ▁ of ▁ binary ▁ tree ▁ : ▁ " NEW_LINE for i in diagonalPrintMap : NEW_LINE INDENT for j in diagonalPrintMap [ i ] : NEW_LINE INDENT print j , NEW_LINE DEDENT print " " NEW_LINE DEDENT DEDENT root = Node ( 8 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 10 ) NEW_LINE root . left . left = Node ( 1 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . right . right = Node ( 14 ) NEW_LINE root . right . right . left = Node ( 13 ) NEW_LINE root . left . right . left = Node ( 4 ) NEW_LINE root . left . right . right = Node ( 7 ) NEW_LINE diagonalPrint ( root ) NEW_LINE
Doubly Linked List | Set 1 ( Introduction and Insertion ) | Adding a node at the front of the list ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new node as head and previous as NULL ; 4. change prev of head node to new node ; 5. move the head to point to the new node
def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( data = new_data ) NEW_LINE new_node . next = self . head NEW_LINE new_node . prev = None NEW_LINE if self . head is not None : NEW_LINE INDENT self . head . prev = new_node NEW_LINE DEDENT self . head = new_node NEW_LINE DEDENT
Doubly Linked List | Set 1 ( Introduction and Insertion ) | Given a node as prev_node , insert a new node after the given node ; 1. check if the given prev_node is NULL ; 2. allocate node & 3. put in the data ; 4. Make next of new node as next of prev_node ; 5. Make the next of prev_node as new_node ; 6. Make prev_node as previous of new_node ; 7. Change previous of new_node 's next node
def insertAfter ( self , prev_node , new_data ) : NEW_LINE INDENT if prev_node is None : NEW_LINE INDENT print ( " This ▁ node ▁ doesn ' t ▁ exist ▁ in ▁ DLL " ) NEW_LINE return NEW_LINE DEDENT new_node = Node ( data = new_data ) NEW_LINE new_node . next = prev_node . next NEW_LINE prev_node . next = new_node NEW_LINE new_node . prev = prev_node NEW_LINE if new_node . next is not None : NEW_LINE INDENT new_node . next . prev = new_node NEW_LINE DEDENT DEDENT
Doubly Linked List | Set 1 ( Introduction and Insertion ) | Add a node at the end of the DLL ; 1. allocate node 2. put in the data ; 3. This new node is going to be the last node , so make next of it as NULL ; 4. If the Linked List is empty , then make the new node as head ; 5. Else traverse till the last node ; 6. Change the next of last node ; 7. Make last node as previous of new node
def append ( self , new_data ) : NEW_LINE INDENT new_node = Node ( data = new_data ) NEW_LINE last = self . head NEW_LINE new_node . next = None NEW_LINE if self . head is None : NEW_LINE INDENT new_node . prev = None NEW_LINE self . head = new_node NEW_LINE return NEW_LINE DEDENT while ( last . next is not None ) : NEW_LINE INDENT last = last . next NEW_LINE DEDENT last . next = new_node NEW_LINE new_node . prev = last NEW_LINE DEDENT
Binary Tree ( Array implementation ) | Python3 implementation of tree using array numbering starting from 0 to n - 1. ; create root ; create left son of root ; create right son of root ; Print tree ; Driver Code
tree = [ None ] * 10 NEW_LINE def root ( key ) : NEW_LINE INDENT if tree [ 0 ] != None : NEW_LINE INDENT print ( " Tree ▁ already ▁ had ▁ root " ) NEW_LINE DEDENT else : NEW_LINE INDENT tree [ 0 ] = key NEW_LINE DEDENT DEDENT def set_left ( key , parent ) : NEW_LINE INDENT if tree [ parent ] == None : NEW_LINE INDENT print ( " Can ' t ▁ set ▁ child ▁ at " , ( parent * 2 ) + 1 , " , ▁ no ▁ parent ▁ found " ) NEW_LINE DEDENT else : NEW_LINE INDENT tree [ ( parent * 2 ) + 1 ] = key NEW_LINE DEDENT DEDENT def set_right ( key , parent ) : NEW_LINE INDENT if tree [ parent ] == None : NEW_LINE INDENT print ( " Can ' t ▁ set ▁ child ▁ at " , ( parent * 2 ) + 2 , " , ▁ no ▁ parent ▁ found " ) NEW_LINE DEDENT else : NEW_LINE INDENT tree [ ( parent * 2 ) + 2 ] = key NEW_LINE DEDENT DEDENT def print_tree ( ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT if tree [ i ] != None : NEW_LINE INDENT print ( tree [ i ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - " , end = " " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT root ( ' A ' ) NEW_LINE set_right ( ' C ' , 0 ) NEW_LINE set_left ( ' D ' , 1 ) NEW_LINE set_right ( ' E ' , 1 ) NEW_LINE set_right ( ' F ' , 2 ) NEW_LINE print_tree ( ) NEW_LINE
Swap Kth node from beginning with Kth node from end in a Linked List | A Linked List node ; Utility function to insert a node at the beginning @ args : data : value of node ; Print linked list ; count number of node in linked list ; Function for swapping kth nodes from both ends of linked list ; Count nodes in linked list ; check if k is valid ; If x ( kth node from start ) and y ( kth node from end ) are same ; Find the kth node from beginning of linked list . We also find previous of kth node because we need to update next pointer of the previous . ; Similarly , find the kth node from end and its previous . kth node from end is ( n - k + 1 ) th node from beginning ; If x_prev exists , then new next of it will be y . Consider the case when y -> next is x , in this case , x_prev and y are same . So the statement " x _ prev - > next ▁ = ▁ y " creates a self loop . This self loop will be broken when we change y -> next . ; Same thing applies to y_prev ; Swap next pointers of x and y . These statements also break self loop if x -> next is y or y -> next is x ; Change head pointers when k is 1 or n ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , data , next = None ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = next NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self , * args , ** kwargs ) : NEW_LINE INDENT self . head = Node ( None ) NEW_LINE DEDENT def push ( self , data ) : NEW_LINE INDENT node = Node ( data ) NEW_LINE node . next = self . head NEW_LINE self . head = node NEW_LINE DEDENT def printList ( self ) : NEW_LINE INDENT node = self . head NEW_LINE while node . next is not None : NEW_LINE INDENT print ( node . data , end = " ▁ " ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT def countNodes ( self ) : NEW_LINE INDENT count = 0 NEW_LINE node = self . head NEW_LINE while node . next is not None : NEW_LINE INDENT count += 1 NEW_LINE node = node . next NEW_LINE DEDENT return count NEW_LINE DEDENT def swapKth ( self , k ) : NEW_LINE INDENT n = self . countNodes ( ) NEW_LINE if n < k : NEW_LINE INDENT return NEW_LINE DEDENT if ( 2 * k - 1 ) == n : NEW_LINE INDENT return NEW_LINE DEDENT x = self . head NEW_LINE x_prev = Node ( None ) NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT x_prev = x NEW_LINE x = x . next NEW_LINE DEDENT y = self . head NEW_LINE y_prev = Node ( None ) NEW_LINE for i in range ( n - k ) : NEW_LINE INDENT y_prev = y NEW_LINE y = y . next NEW_LINE DEDENT if x_prev is not None : NEW_LINE INDENT x_prev . next = y NEW_LINE DEDENT if y_prev is not None : NEW_LINE INDENT y_prev . next = x NEW_LINE DEDENT temp = x . next NEW_LINE x . next = y . next NEW_LINE y . next = temp NEW_LINE if k == 1 : NEW_LINE INDENT self . head = y NEW_LINE DEDENT if k == n : NEW_LINE INDENT self . head = x NEW_LINE DEDENT DEDENT DEDENT llist = LinkedList ( ) NEW_LINE for i in range ( 8 , 0 , - 1 ) : NEW_LINE INDENT llist . push ( i ) NEW_LINE DEDENT llist . printList ( ) NEW_LINE for i in range ( 1 , 9 ) : NEW_LINE INDENT llist . swapKth ( i ) NEW_LINE print ( " Modified ▁ List ▁ for ▁ k ▁ = ▁ " , i ) NEW_LINE llist . printList ( ) NEW_LINE print ( " " ) NEW_LINE DEDENT
Find pairs with given sum in doubly linked list | Structure of node of doubly linked list ; Function to find pair whose sum equal to given value x . ; Set two pointers , first to the beginning of DLL and second to the end of DLL . ; To track if we find a pair or not ; The loop terminates when they cross each other ( second . next == first ) , or they become same ( first == second ) ; Pair found ; Move first in forward direction ; Move second in backward direction ; If pair is not present ; A utility function to insert a new node at the beginning of doubly linked list ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT def pairSum ( head , x ) : NEW_LINE INDENT first = head NEW_LINE second = head NEW_LINE while ( second . next != None ) : NEW_LINE INDENT second = second . next NEW_LINE DEDENT found = False NEW_LINE while ( first != second and second . next != first ) : NEW_LINE INDENT if ( ( first . data + second . data ) == x ) : NEW_LINE INDENT found = True NEW_LINE print ( " ( " , first . data , " , " , second . data , " ) " ) NEW_LINE first = first . next NEW_LINE second = second . prev NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( first . data + second . data ) < x ) : NEW_LINE INDENT first = first . next NEW_LINE DEDENT else : NEW_LINE INDENT second = second . prev NEW_LINE DEDENT DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT print ( " No ▁ pair ▁ found " ) NEW_LINE DEDENT DEDENT def insert ( head , data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE if not head : NEW_LINE INDENT head = temp NEW_LINE DEDENT else : NEW_LINE INDENT temp . next = head NEW_LINE head . prev = temp NEW_LINE head = temp NEW_LINE DEDENT return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = insert ( head , 9 ) NEW_LINE head = insert ( head , 8 ) NEW_LINE head = insert ( head , 6 ) NEW_LINE head = insert ( head , 5 ) NEW_LINE head = insert ( head , 4 ) NEW_LINE head = insert ( head , 2 ) NEW_LINE head = insert ( head , 1 ) NEW_LINE x = 7 NEW_LINE pairSum ( head , x ) NEW_LINE DEDENT
Iterative diagonal traversal of binary tree | A binary tree node has data , pointer to left child and a pointer to right child ; Function to print diagonal view ; base case ; queue of treenode ; Append root ; Append delimiter ; If current is delimiter then insert another for next diagonal and cout nextline ; If queue is empty then return ; Print output on nextline ; append delimiter again ; If left child is present append into queue ; current equals to right child ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . val = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def diagonalprint ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE q . append ( None ) NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT temp = q . pop ( 0 ) NEW_LINE if not temp : NEW_LINE INDENT if len ( q ) == 0 : NEW_LINE INDENT return NEW_LINE DEDENT print ( ' ▁ ' ) NEW_LINE q . append ( None ) NEW_LINE DEDENT else : NEW_LINE INDENT while temp : NEW_LINE INDENT print ( temp . val , end = ' ▁ ' ) NEW_LINE if temp . left : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT temp = temp . right NEW_LINE DEDENT DEDENT DEDENT DEDENT root = Node ( 8 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 10 ) NEW_LINE root . left . left = Node ( 1 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . right . right = Node ( 14 ) NEW_LINE root . right . right . left = Node ( 13 ) NEW_LINE root . left . right . left = Node ( 4 ) NEW_LINE root . left . right . right = Node ( 7 ) NEW_LINE diagonalprint ( root ) NEW_LINE
Count triplets in a sorted doubly linked list whose sum is equal to a given value x | Structure of node of doubly linked list ; Function to count pairs whose sum equal to given 'value ; The loop terminates when either of two pointers become None , or they cross each other ( second . next == first ) , or they become same ( first == second ) ; Pair found ; Increment count ; Move first in forward direction ; Move second in backward direction ; If sum is greater than ' value ' move second in backward direction ; Else move first in forward direction ; Required count of pairs ; Function to count triplets in a sorted doubly linked list whose sum is equal to a given value 'x ; If list is empty ; Get pointer to the last node of the doubly linked list ; Traversing the doubly linked list ; For each current node ; count pairs with sum ( x - current . data ) in the range first to last and add it to the ' count ' of triplets ; Required count of triplets ; A utility function to insert a new node at the beginning of doubly linked list ; Allocate node ; Put in the data temp . next = temp . prev = None ; Driver code ; Start with an empty doubly linked list ; Insert values in sorted order
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT def countPairs ( first , second , value ) : NEW_LINE INDENT count = 0 NEW_LINE while ( first != None and second != None and first != second and second . next != first ) : NEW_LINE INDENT if ( ( first . data + second . data ) == value ) : NEW_LINE INDENT count += 1 NEW_LINE first = first . next NEW_LINE second = second . prev NEW_LINE DEDENT elif ( ( first . data + second . data ) > value ) : NEW_LINE INDENT second = second . prev NEW_LINE DEDENT else : NEW_LINE INDENT first = first . next NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def countTriplets ( head , x ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT current , first , last = head , None , None NEW_LINE count = 0 NEW_LINE last = head NEW_LINE while ( last . next != None ) : NEW_LINE INDENT last = last . next NEW_LINE DEDENT while current != None : NEW_LINE INDENT first = current . next NEW_LINE count , current = count + countPairs ( first , last , x - current . data ) , current . next NEW_LINE DEDENT return count NEW_LINE DEDENT def insert ( head , data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE if ( head == None ) : NEW_LINE INDENT head = temp NEW_LINE DEDENT else : NEW_LINE INDENT temp . next = head NEW_LINE head . prev = temp NEW_LINE head = temp NEW_LINE DEDENT return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = insert ( head , 9 ) NEW_LINE head = insert ( head , 8 ) NEW_LINE head = insert ( head , 6 ) NEW_LINE head = insert ( head , 5 ) NEW_LINE head = insert ( head , 4 ) NEW_LINE head = insert ( head , 2 ) NEW_LINE head = insert ( head , 1 ) NEW_LINE x = 17 NEW_LINE print ( " Count ▁ = ▁ " , countTriplets ( head , x ) ) NEW_LINE DEDENT
Remove duplicates from an unsorted doubly linked list | Node of a linked list ; Function to delete a node in a Doubly Linked List . head_ref - . pointer to head node pointer . del - . pointer to node to be deleted . ; base case ; If node to be deleted is head node ; Change next only if node to be deleted is NOT the last node ; Change prev only if node to be deleted is NOT the first node ; function to remove duplicates from an unsorted doubly linked list ; if DLL is empty or if it contains only a single node ; pick elements one by one ; Compare the picked element with the rest of the elements ; if duplicate , then delete it ; store pointer to the node next to 'ptr2 ; delete node pointed to by 'ptr2 ; update 'ptr2 ; else simply move to the next node ; Function to insert a node at the beginning of the Doubly Linked List ; allocate node ; put in the data ; since we are adding at the beginning , prev is always None ; link the old list off the new node ; change prev of head node to new node ; move the head to point to the new node ; Function to print nodes in a given doubly linked list ; if list is empty ; Driver Code ; Create the doubly linked list : 8 < .4 < .4 < .6 < .4 < .8 < .4 < .10 < .12 < .12 ; remove duplicate nodes
class Node : NEW_LINE INDENT def __init__ ( self , data = None , next = None ) : NEW_LINE INDENT self . next = next NEW_LINE self . data = data NEW_LINE DEDENT DEDENT def deleteNode ( head_ref , del_ ) : NEW_LINE INDENT if ( head_ref == None or del_ == None ) : NEW_LINE INDENT return head_ref NEW_LINE DEDENT if ( head_ref == del_ ) : NEW_LINE INDENT head_ref = del_ . next NEW_LINE DEDENT if ( del_ . next != None ) : NEW_LINE INDENT del_ . next . prev = del_ . prev NEW_LINE DEDENT if ( del_ . prev != None ) : NEW_LINE INDENT del_ . prev . next = del_ . next NEW_LINE DEDENT return head_ref NEW_LINE DEDENT def removeDuplicates ( head_ref ) : NEW_LINE INDENT if ( ( head_ref ) == None or ( head_ref ) . next == None ) : NEW_LINE INDENT return head_ref NEW_LINE DEDENT ptr1 = head_ref NEW_LINE ptr2 = None NEW_LINE while ( ptr1 != None ) : NEW_LINE INDENT ptr2 = ptr1 . next NEW_LINE while ( ptr2 != None ) : NEW_LINE INDENT if ( ptr1 . data == ptr2 . data ) : NEW_LINE INDENT next = ptr2 . next NEW_LINE head_ref = deleteNode ( head_ref , ptr2 ) NEW_LINE ptr2 = next NEW_LINE DEDENT else : NEW_LINE INDENT ptr2 = ptr2 . next NEW_LINE DEDENT DEDENT ptr1 = ptr1 . next NEW_LINE DEDENT return head_ref NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . prev = None NEW_LINE new_node . next = ( head_ref ) NEW_LINE if ( ( head_ref ) != None ) : NEW_LINE INDENT ( head_ref ) . prev = new_node NEW_LINE DEDENT ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT print ( " Doubly ▁ Linked ▁ list ▁ empty " ) NEW_LINE DEDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " ▁ " ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT head = None NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 10 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 8 ) NEW_LINE print ( " Original ▁ Doubly ▁ linked ▁ list : " ) NEW_LINE printList ( head ) NEW_LINE head = removeDuplicates ( head ) NEW_LINE print ( " Doubly linked list after removing duplicates : " ) NEW_LINE printList ( head ) NEW_LINE
Remove duplicates from an unsorted doubly linked list | a node of the doubly linked list ; Function to delete a node in a Doubly Linked List . head_ref -- > pointer to head node pointer . del -- > pointer to node to be deleted . ; base case ; If node to be deleted is head node ; Change next only if node to be deleted is NOT the last node ; Change prev only if node to be deleted is NOT the first node ; function to remove duplicates from an unsorted doubly linked list ; if doubly linked list is empty ; unordered_set ' us ' implemented as hash table ; traverse up to the end of the list ; if current data is seen before ; store pointer to the node next to ' current ' node ; delete the node pointed to by 'current ; update 'current ; insert the current data in 'us ; move to the next node ; Function to insert a node at the beginning of the Doubly Linked List ; allocate node ; put in the data ; since we are adding at the beginning , prev is always None ; link the old list off the new node ; change prev of head node to new node ; move the head to point to the new node ; Function to print nodes in a given doubly linked list ; if list is empty ; Driver Code ; Create the doubly linked list : 8 < -> 4 < -> 4 < -> 6 < -> 4 < -> 8 < -> 4 < -> 10 < -> 12 < -> 12 ; remove duplicate nodes
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT def deleteNode ( head_ref , del_ ) : NEW_LINE INDENT if ( head_ref == None or del_ == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( head_ref == del_ ) : NEW_LINE INDENT head_ref = del_ . next NEW_LINE DEDENT if ( del_ . next != None ) : NEW_LINE INDENT del_ . next . prev = del_ . prev NEW_LINE DEDENT if ( del_ . prev != None ) : NEW_LINE INDENT del_ . prev . next = del_ . next NEW_LINE DEDENT return head_ref NEW_LINE DEDENT def removeDuplicates ( head_ref ) : NEW_LINE INDENT if ( ( head_ref ) == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT us = set ( ) NEW_LINE current = head_ref NEW_LINE next = None NEW_LINE while ( current != None ) : NEW_LINE INDENT if ( ( current . data ) in us ) : NEW_LINE INDENT next = current . next NEW_LINE head_ref = deleteNode ( head_ref , current ) NEW_LINE current = next NEW_LINE DEDENT else : NEW_LINE INDENT us . add ( current . data ) NEW_LINE current = current . next NEW_LINE DEDENT DEDENT return head_ref NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . prev = None NEW_LINE new_node . next = ( head_ref ) NEW_LINE if ( ( head_ref ) != None ) : NEW_LINE INDENT ( head_ref ) . prev = new_node NEW_LINE DEDENT ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT print ( " Doubly ▁ Linked ▁ list ▁ empty " ) NEW_LINE DEDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " ▁ " ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT head = None NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 10 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 8 ) NEW_LINE print ( " Original ▁ Doubly ▁ linked ▁ list : " ) NEW_LINE printList ( head ) NEW_LINE head = removeDuplicates ( head ) NEW_LINE print ( " Doubly linked list after removing duplicates : " ) NEW_LINE printList ( head ) NEW_LINE
Sorted insert in a doubly linked list with head and tail pointers | Linked List node ; Function to insetail new node ; If first node to be insetailed in doubly linked list ; If node to be insetailed has value less than first node ; If node to be insetailed has value more than last node ; Find the node before which we need to insert p . ; Insert new node before temp ; Function to print nodes in from left to right ; Driver program to test above functions
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . info = data NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT head = None NEW_LINE tail = None NEW_LINE def nodeInsetail ( key ) : NEW_LINE INDENT global head NEW_LINE global tail NEW_LINE p = Node ( 0 ) NEW_LINE p . info = key NEW_LINE p . next = None NEW_LINE if ( ( head ) == None ) : NEW_LINE INDENT ( head ) = p NEW_LINE ( tail ) = p NEW_LINE ( head ) . prev = None NEW_LINE return NEW_LINE DEDENT if ( ( p . info ) < ( ( head ) . info ) ) : NEW_LINE INDENT p . prev = None NEW_LINE ( head ) . prev = p NEW_LINE p . next = ( head ) NEW_LINE ( head ) = p NEW_LINE return NEW_LINE DEDENT if ( ( p . info ) > ( ( tail ) . info ) ) : NEW_LINE INDENT p . prev = ( tail ) NEW_LINE ( tail ) . next = p NEW_LINE ( tail ) = p NEW_LINE return NEW_LINE DEDENT temp = ( head ) . next NEW_LINE while ( ( temp . info ) < ( p . info ) ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT ( temp . prev ) . next = p NEW_LINE p . prev = temp . prev NEW_LINE temp . prev = p NEW_LINE p . next = temp NEW_LINE DEDENT def printList ( temp ) : NEW_LINE INDENT while ( temp != None ) : NEW_LINE INDENT print ( temp . info , end = " ▁ " ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT nodeInsetail ( 30 ) NEW_LINE nodeInsetail ( 50 ) NEW_LINE nodeInsetail ( 90 ) NEW_LINE nodeInsetail ( 10 ) NEW_LINE nodeInsetail ( 40 ) NEW_LINE nodeInsetail ( 110 ) NEW_LINE nodeInsetail ( 60 ) NEW_LINE nodeInsetail ( 95 ) NEW_LINE nodeInsetail ( 23 ) NEW_LINE print ( " Doubly linked list on printing from left to right " ) NEW_LINE printList ( head ) NEW_LINE
Doubly Circular Linked List | Set 1 ( Introduction and Insertion ) | Structure of a Node ; Function to insert at the end ; If the list is empty , create a single node circular and doubly list ; Find last node ; Create Node dynamically ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last ; Function to insert Node at the beginning of the List , ; Pointer points to last Node ; Inserting the data ; setting up previous and next of new node ; Update next and previous pointers of start and last . ; Update start pointer ; Function to insert node with value as value1 . The new node is inserted after the node with with value2 ; Inserting the data ; Find node having value2 and next node of it ; insert new_node between temp and next . ; Driver Code ; Start with the empty list ; Insert 5. So linked list becomes 5. None ; Insert 4 at the beginning . So linked list becomes 4.5 ; Insert 7 at the end . So linked list becomes 4.5 . 7 ; Insert 8 at the end . So linked list becomes 4.5 . 7.8 ; Insert 6 , after 5. So linked list becomes 4.5 . 6.7 . 8
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT def insertEnd ( value ) : NEW_LINE INDENT global start NEW_LINE if ( start == None ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE new_node . data = value NEW_LINE new_node . next = new_node . prev = new_node NEW_LINE start = new_node NEW_LINE return NEW_LINE DEDENT last = ( start ) . prev NEW_LINE new_node = Node ( 0 ) NEW_LINE new_node . data = value NEW_LINE new_node . next = start NEW_LINE ( start ) . prev = new_node NEW_LINE new_node . prev = last NEW_LINE last . next = new_node NEW_LINE DEDENT def insertBegin ( value ) : NEW_LINE INDENT global start NEW_LINE last = ( start ) . prev NEW_LINE new_node = Node ( 0 ) NEW_LINE new_node . data = value NEW_LINE new_node . next = start NEW_LINE new_node . prev = last NEW_LINE last . next = ( start ) . prev = new_node NEW_LINE start = new_node NEW_LINE DEDENT def insertAfter ( value1 , value2 ) : NEW_LINE INDENT global start NEW_LINE new_node = Node ( 0 ) NEW_LINE new_node . data = value1 NEW_LINE temp = start NEW_LINE while ( temp . data != value2 ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT next = temp . next NEW_LINE temp . next = new_node NEW_LINE new_node . prev = temp NEW_LINE new_node . next = next NEW_LINE next . prev = new_node NEW_LINE DEDENT def display ( ) : NEW_LINE INDENT global start NEW_LINE temp = start NEW_LINE print ( " Traversal ▁ in ▁ forward ▁ direction : " ) NEW_LINE while ( temp . next != start ) : NEW_LINE INDENT print ( temp . data , end = " ▁ " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( temp . data ) NEW_LINE print ( " Traversal ▁ in ▁ reverse ▁ direction : " ) NEW_LINE last = start . prev NEW_LINE temp = last NEW_LINE while ( temp . prev != last ) : NEW_LINE INDENT print ( temp . data , end = " ▁ " ) NEW_LINE temp = temp . prev NEW_LINE DEDENT print ( temp . data ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT global start NEW_LINE start = None NEW_LINE insertEnd ( 5 ) NEW_LINE insertBegin ( 4 ) NEW_LINE insertEnd ( 7 ) NEW_LINE insertEnd ( 8 ) NEW_LINE insertAfter ( 6 , 5 ) NEW_LINE print ( " Created ▁ circular ▁ doubly ▁ linked ▁ list ▁ is : ▁ " ) NEW_LINE display ( ) NEW_LINE DEDENT
Boundary Traversal of binary tree | A binary tree node ; A simple function to print leaf nodes of a Binary Tree ; Print it if it is a leaf node ; A function to print all left boundary nodes , except a leaf node . Print the nodes in TOP DOWN manner ; to ensure top down order , print the node before calling itself for left subtree ; A function to print all right boundary nodes , except a leaf node . Print the nodes in BOTTOM UP manner ; to ensure bottom up order , first call for right subtree , then print this node ; A function to do boundary traversal of a given binary tree ; Print the left boundary in top - down manner ; Print all leaf nodes ; Print the right boundary in bottom - up manner ; Driver program to test above function
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printLeaves ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT printLeaves ( root . left ) NEW_LINE if root . left is None and root . right is None : NEW_LINE INDENT print ( root . data ) , NEW_LINE DEDENT printLeaves ( root . right ) NEW_LINE DEDENT DEDENT def printBoundaryLeft ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT if ( root . left ) : NEW_LINE INDENT print ( root . data ) NEW_LINE printBoundaryLeft ( root . left ) NEW_LINE DEDENT elif ( root . right ) : NEW_LINE INDENT print ( root . data ) NEW_LINE printBoundaryLeft ( root . right ) NEW_LINE DEDENT DEDENT DEDENT def printBoundaryRight ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT if ( root . right ) : NEW_LINE INDENT printBoundaryRight ( root . right ) NEW_LINE print ( root . data ) NEW_LINE DEDENT elif ( root . left ) : NEW_LINE INDENT printBoundaryRight ( root . left ) NEW_LINE print ( root . data ) NEW_LINE DEDENT DEDENT DEDENT def printBoundary ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT print ( root . data ) NEW_LINE printBoundaryLeft ( root . left ) NEW_LINE printLeaves ( root . left ) NEW_LINE printLeaves ( root . right ) NEW_LINE printBoundaryRight ( root . right ) NEW_LINE DEDENT DEDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE printBoundary ( root ) NEW_LINE
An interesting method to print reverse of a linked list | Link list node ; Function to reverse the linked list ; For each node , print proper number of spaces before printing it ; use of carriage return to move back and print . ; Function to push a node ; Function to print linked list and find its length ; i for finding length of list ; Start with the empty list ; list nodes are as 6 5 4 3 2 1 ; printlist print the list and return the size of list ; print reverse list with help of carriage return function
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def printReverse ( head_ref , n ) : NEW_LINE INDENT j = 0 NEW_LINE current = head_ref NEW_LINE while ( current != None ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < 2 * ( n - j ) ) : NEW_LINE INDENT print ( end = " ▁ " ) NEW_LINE i = i + 1 NEW_LINE DEDENT print ( current . data , end = " " ) NEW_LINE current = current . next NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref ; NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT i = 0 NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = " ▁ " ) NEW_LINE temp = temp . next NEW_LINE i = i + 1 NEW_LINE DEDENT return i NEW_LINE DEDENT head = None NEW_LINE head = push ( head , 1 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 6 ) NEW_LINE print ( " Given ▁ linked ▁ list : " ) NEW_LINE n = printList ( head ) NEW_LINE print ( " Reversed Linked list : " ) NEW_LINE printReverse ( head , n ) NEW_LINE print ( ) NEW_LINE
Practice questions for Linked List and Recursion |
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT
Practice questions for Linked List and Recursion |
def fun1 ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT fun1 ( head . next ) NEW_LINE print ( head . data , end = " ▁ " ) NEW_LINE DEDENT
Practice questions for Linked List and Recursion |
def fun2 ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( head . data , end = " ▁ " ) NEW_LINE if ( head . next != None ) : NEW_LINE INDENT fun2 ( head . next . next ) NEW_LINE DEDENT print ( head . data , end = " ▁ " ) NEW_LINE DEDENT
Practice questions for Linked List and Recursion | A linked list node ; Prints a linked list in reverse manner ; prints alternate nodes of a Linked List , first from head to end , and then from end to head . ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; put in the data ; link the old list off the new node ; move the head to poto the new node ; Start with the empty list ; Using push ( ) to construct below list 1.2 . 3.4 . 5
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def fun1 ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT fun1 ( head . next ) NEW_LINE print ( head . data , end = " ▁ " ) NEW_LINE DEDENT def fun2 ( start ) : NEW_LINE INDENT if ( start == None ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( start . data , end = " ▁ " ) NEW_LINE if ( start . next != None ) : NEW_LINE INDENT fun2 ( start . next . next ) NEW_LINE DEDENT print ( start . data , end = " ▁ " ) NEW_LINE DEDENT def push ( head , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = head NEW_LINE head = new_node NEW_LINE return head NEW_LINE DEDENT head = None NEW_LINE head = Node ( 5 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 1 ) NEW_LINE print ( " Output ▁ of ▁ fun1 ( ) ▁ for ▁ list ▁ 1 - > 2 - > 3 - > 4 - > 5" ) NEW_LINE fun1 ( head ) NEW_LINE print ( " Output of fun2 ( ) for list 1 -> 2 -> 3 -> 4 -> 5 " ) NEW_LINE fun2 ( head ) NEW_LINE
Density of Binary Tree in One Traversal | A binary tree node ; Function to compute height and size of a binary tree ; compute height of each subtree ; increase size by 1 ; return larger of the two ; function to calculate density of a binary tree ; To store size ; Finds height and size ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def heighAndSize ( node , size ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l = heighAndSize ( node . left , size ) NEW_LINE r = heighAndSize ( node . right , size ) NEW_LINE size [ 0 ] += 1 NEW_LINE return l + 1 if ( l > r ) else r + 1 NEW_LINE DEDENT def density ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT size = [ 0 ] NEW_LINE _height = heighAndSize ( root , size ) NEW_LINE return size [ 0 ] / _height NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE print ( " Density ▁ of ▁ given ▁ binary ▁ tree ▁ is ▁ " , density ( root ) ) NEW_LINE DEDENT
Squareroot ( n ) | Python3 program to find sqrt ( n ) 'th node of a linked list Node class ; Function to initialise the node object ; Function to get the sqrt ( n ) th node of a linked list ; Traverse the list ; check if j = sqrt ( i ) ; for first node ; increment j if j = sqrt ( i ) ; return node 's data ; function to add a new node at the beginning of the list ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver Code ; Start with the empty list
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def printsqrtn ( head ) : NEW_LINE INDENT sqrtn = None NEW_LINE i = 1 NEW_LINE j = 1 NEW_LINE while ( head != None ) : NEW_LINE INDENT if ( i == j * j ) : NEW_LINE INDENT if ( sqrtn == None ) : NEW_LINE INDENT sqrtn = head NEW_LINE DEDENT else : NEW_LINE INDENT sqrtn = sqrtn . next NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE head = head . next NEW_LINE DEDENT return sqrtn . data NEW_LINE DEDENT def print_1 ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " ▁ " ) NEW_LINE head = head . next NEW_LINE DEDENT print ( " ▁ " ) NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 40 ) NEW_LINE head = push ( head , 30 ) NEW_LINE head = push ( head , 20 ) NEW_LINE head = push ( head , 10 ) NEW_LINE print ( " Given ▁ linked ▁ list ▁ is : " ) NEW_LINE print_1 ( head ) NEW_LINE print ( " sqrt ( n ) th ▁ node ▁ is ▁ " , printsqrtn ( head ) ) NEW_LINE DEDENT
Find the fractional ( or n / k | Python3 program to find fractional node in a linked list ; Linked list node ; Function to create a new node with given data ; Function to find fractional node in the linked list ; Corner cases ; Traverse the given list ; For every k nodes , we move fractionalNode one step ahead . ; First time we see a multiple of k ; A utility function to print a linked list ; Driver Code
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT new_node = Node ( data ) NEW_LINE new_node . data = data NEW_LINE new_node . next = None NEW_LINE return new_node NEW_LINE DEDENT def fractionalNodes ( head , k ) : NEW_LINE INDENT if ( k <= 0 or head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT fractionalNode = None NEW_LINE i = 0 NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT if ( i % k == 0 ) : NEW_LINE INDENT if ( fractionalNode == None ) : NEW_LINE INDENT fractionalNode = head NEW_LINE DEDENT else : NEW_LINE INDENT fractionalNode = fractionalNode . next NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE temp = temp . next NEW_LINE DEDENT return fractionalNode NEW_LINE DEDENT def prList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = ' ▁ ' ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next = newNode ( 5 ) NEW_LINE k = 2 NEW_LINE print ( " List ▁ is " , end = ' ▁ ' ) NEW_LINE prList ( head ) NEW_LINE answer = fractionalNodes ( head , k ) NEW_LINE print ( " Fractional node is " , end = ' ▁ ' ) NEW_LINE print ( answer . data ) NEW_LINE DEDENT
Find modular node in a linked list | Python3 program to find modular node in a linked list ; Linked list node ; Function to create a new node with given data ; Function to find modular node in the linked list ; Corner cases ; Traverse the given list ; Driver Code
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT new_node = Node ( data ) NEW_LINE new_node . data = data NEW_LINE new_node . next = None NEW_LINE return new_node NEW_LINE DEDENT def modularNode ( head , k ) : NEW_LINE INDENT if ( k <= 0 or head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT i = 1 NEW_LINE modularNode = None NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT if ( i % k == 0 ) : NEW_LINE INDENT modularNode = temp NEW_LINE DEDENT i = i + 1 NEW_LINE temp = temp . next NEW_LINE DEDENT return modularNode NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next = newNode ( 5 ) NEW_LINE k = 2 NEW_LINE answer = modularNode ( head , k ) NEW_LINE print ( " Modular ▁ node ▁ is " , end = ' ▁ ' ) NEW_LINE if ( answer != None ) : NEW_LINE INDENT print ( answer . data , end = ' ▁ ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " None " ) NEW_LINE DEDENT DEDENT
Modify contents of Linked List | Linked list node ; Function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list at the end of the new node ; move the head to point to the new node ; Split the nodes of the given list into front and back halves , and return the two lists using the reference parameters . Uses the fast / slow pointer strategy . ; Advance ' fast ' two nodes , and advance ' slow ' one node ; ' slow ' is before the midpoint in the list , so split it in two at that point . ; Function to reverse the linked list ; perfrom the required subtraction operation on the 1 st half of the linked list ; traversing both the lists simultaneously ; subtraction operation and node data modification ; function to concatenate the 2 nd ( back ) list at the end of the 1 st ( front ) list and returns the head of the new list ; function to modify the contents of the linked list ; if list is empty or contains only single node ; split the list into two halves front and back lists ; reverse the 2 nd ( back ) list ; modify the contents of 1 st half ; agains reverse the 2 nd ( back ) list ; concatenating the 2 nd list back to the end of the 1 st list ; pointer to the modified list ; function to print the linked list ; Driver Code ; creating the linked list ; modify the linked list ; print the modified linked list
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT front = None NEW_LINE back = None NEW_LINE def frontAndBackSplit ( head ) : NEW_LINE INDENT global front NEW_LINE global back NEW_LINE slow = None NEW_LINE fast = None NEW_LINE slow = head NEW_LINE fast = head . next NEW_LINE while ( fast != None ) : NEW_LINE INDENT fast = fast . next NEW_LINE if ( fast != None ) : NEW_LINE INDENT slow = slow . next NEW_LINE fast = fast . next NEW_LINE DEDENT DEDENT front = head NEW_LINE back = slow . next NEW_LINE slow . next = None NEW_LINE return head NEW_LINE DEDENT def reverseList ( head_ref ) : NEW_LINE INDENT current = None NEW_LINE prev = None NEW_LINE next = None NEW_LINE current = head_ref NEW_LINE prev = None NEW_LINE while ( current != None ) : NEW_LINE INDENT next = current . next NEW_LINE current . next = prev NEW_LINE prev = current NEW_LINE current = next NEW_LINE DEDENT head_ref = prev NEW_LINE return head_ref NEW_LINE DEDENT def modifyTheContentsOf1stHalf ( ) : NEW_LINE INDENT global front NEW_LINE global back NEW_LINE front1 = front NEW_LINE back1 = back NEW_LINE while ( back1 != None ) : NEW_LINE INDENT front1 . data = front1 . data - back1 . data NEW_LINE front1 = front1 . next NEW_LINE back1 = back1 . next NEW_LINE DEDENT DEDENT def concatFrontAndBackList ( front , back ) : NEW_LINE INDENT head = front NEW_LINE if ( front == None ) : NEW_LINE INDENT return back NEW_LINE DEDENT while ( front . next != None ) : NEW_LINE INDENT front = front . next NEW_LINE DEDENT front . next = back NEW_LINE return head NEW_LINE DEDENT def modifyTheList ( head ) : NEW_LINE INDENT global front NEW_LINE global back NEW_LINE if ( head == None or head . next == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT front = None NEW_LINE back = None NEW_LINE frontAndBackSplit ( head ) NEW_LINE back = reverseList ( back ) NEW_LINE modifyTheContentsOf1stHalf ( ) NEW_LINE back = reverseList ( back ) NEW_LINE head = concatFrontAndBackList ( front , back ) NEW_LINE return head NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT while ( head . next != None ) : NEW_LINE INDENT print ( head . data , " ▁ - > ▁ " , end = " " ) NEW_LINE head = head . next NEW_LINE DEDENT print ( head . data ) NEW_LINE DEDENT head = None NEW_LINE head = push ( head , 10 ) NEW_LINE head = push ( head , 7 ) NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 9 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = modifyTheList ( head ) NEW_LINE print ( " Modified ▁ List : " ) NEW_LINE printList ( head ) NEW_LINE
Modify contents of Linked List | Linked list node ; Function to insert a node at the beginning of the linked list ; Allocate node ; Put in the data ; Link the old list at the end of the new node ; Move the head to point to the new node ; Function to print the linked list ; Function to middle node of list . ; Advance ' fast ' two nodes , and advance ' slow ' one node ; If number of nodes are odd then update slow by slow . next ; ; Function to modify the contents of the linked list . ; Create Stack . ; Traverse the list by using temp until stack is empty . ; Driver code ; creating the linked list ; Call Function to Find the starting point of second half of list . ; Call function to modify the contents of the linked list . ; Print the modified linked list
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def append ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT if ( not head ) : NEW_LINE INDENT return ; NEW_LINE DEDENT while ( head . next != None ) : NEW_LINE INDENT print ( head . data , end = ' ▁ - > ▁ ' ) NEW_LINE head = head . next NEW_LINE DEDENT print ( head . data ) NEW_LINE DEDENT def find_mid ( head ) : NEW_LINE INDENT temp = head NEW_LINE slow = head NEW_LINE fast = head NEW_LINE while ( fast and fast . next ) : NEW_LINE INDENT slow = slow . next NEW_LINE fast = fast . next . next NEW_LINE DEDENT if ( fast ) : NEW_LINE INDENT slow = slow . next NEW_LINE DEDENT return slow NEW_LINE DEDENT def modifyTheList ( head , slow ) : NEW_LINE INDENT s = [ ] NEW_LINE temp = head NEW_LINE while ( slow ) : NEW_LINE INDENT s . append ( slow . data ) NEW_LINE slow = slow . next NEW_LINE DEDENT while ( len ( s ) != 0 ) : NEW_LINE INDENT temp . data = temp . data - s [ - 1 ] NEW_LINE temp = temp . next NEW_LINE s . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = append ( head , 10 ) NEW_LINE head = append ( head , 7 ) NEW_LINE head = append ( head , 12 ) NEW_LINE head = append ( head , 8 ) NEW_LINE head = append ( head , 9 ) NEW_LINE head = append ( head , 2 ) NEW_LINE mid = find_mid ( head ) NEW_LINE modifyTheList ( head , mid ) NEW_LINE print ( " Modified ▁ List : " ) NEW_LINE printList ( head ) NEW_LINE DEDENT
Binary Search Tree | Set 1 ( Search and Insertion ) | A utility function to search a given key in BST ; Base Cases : root is null or key is present at root ; Key is greater than root 's key ; Key is smaller than root 's key
def search ( root , key ) : NEW_LINE INDENT if root is None or root . val == key : NEW_LINE INDENT return root NEW_LINE DEDENT if root . val < key : NEW_LINE INDENT return search ( root . right , key ) NEW_LINE DEDENT return search ( root . left , key ) NEW_LINE DEDENT
Modify a binary tree to get preorder traversal using right pointers only | A binary tree node has data , left child and right child ; Function to modify tree ; if the left tree exists ; get the right - most of the original left subtree ; set root right to left subtree ; if the right subtree does not exists we are done ! ; set right pointer of right - most of the original left subtree ; modify the rightsubtree ; printing using right pointer only ; Driver code ; Constructed binary tree is 10 / \ 8 2 / \ 3 5
class newNode ( ) : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def modifytree ( root ) : NEW_LINE INDENT right = root . right NEW_LINE rightMost = root NEW_LINE if ( root . left ) : NEW_LINE INDENT rightMost = modifytree ( root . left ) NEW_LINE root . right = root . left NEW_LINE root . left = None NEW_LINE DEDENT if ( not right ) : NEW_LINE INDENT return rightMost NEW_LINE DEDENT rightMost . right = right NEW_LINE rightMost = modifytree ( right ) NEW_LINE return rightMost NEW_LINE DEDENT def printpre ( root ) : NEW_LINE INDENT while ( root != None ) : NEW_LINE INDENT print ( root . data , end = " ▁ " ) NEW_LINE root = root . right NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 8 ) NEW_LINE root . right = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE modifytree ( root ) NEW_LINE printpre ( root ) NEW_LINE DEDENT
Construct BST from its given level order traversal | Python implementation to construct a BST from its level order traversal ; node of a BST ; function to get a new node ; Allocate memory ; put in the data ; function to construct a BST from its level order traversal ; function to print the inorder traversal ; Driver program
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getNode ( data ) : NEW_LINE INDENT newNode = Node ( data ) NEW_LINE newNode . data = data NEW_LINE newNode . left = None NEW_LINE newNode . right = None NEW_LINE return newNode NEW_LINE DEDENT def LevelOrder ( root , data ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT root = getNode ( data ) NEW_LINE return root NEW_LINE DEDENT if ( data <= root . data ) : NEW_LINE INDENT root . left = LevelOrder ( root . left , data ) NEW_LINE DEDENT else : NEW_LINE INDENT root . right = LevelOrder ( root . right , data ) NEW_LINE DEDENT return root NEW_LINE DEDENT def constructBst ( arr , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return None NEW_LINE DEDENT root = None NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT root = LevelOrder ( root , arr [ i ] ) NEW_LINE DEDENT return root NEW_LINE DEDENT def inorderTraversal ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT inorderTraversal ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE inorderTraversal ( root . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 4 , 12 , 3 , 6 , 8 , 1 , 5 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE root = constructBst ( arr , n ) NEW_LINE print ( " Inorder ▁ Traversal : ▁ " , end = " " ) NEW_LINE root = inorderTraversal ( root ) NEW_LINE DEDENT
Modify a binary tree to get preorder traversal using right pointers only | A binary tree node has data , left child and right child ; An iterative process to set the right pointer of Binary tree ; Base Case ; Create an empty stack and append root to it ; Pop all items one by one . Do following for every popped item a ) prit b ) append its right child c ) append its left child Note that right child is appended first so that left is processed first ; Pop the top item from stack ; append right and left children of the popped node to stack ; check if some previous node exists ; set the right pointer of previous node to currrent ; set previous node as current node ; printing using right pointer only ; Constructed binary tree is 10 / \ 8 2 / \ 3 5
class newNode ( ) : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def modifytree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT nodeStack = [ ] NEW_LINE nodeStack . append ( root ) NEW_LINE pre = None NEW_LINE while ( len ( nodeStack ) ) : NEW_LINE INDENT node = nodeStack [ - 1 ] NEW_LINE nodeStack . pop ( ) NEW_LINE if ( node . right ) : NEW_LINE INDENT nodeStack . append ( node . right ) NEW_LINE DEDENT if ( node . left ) : NEW_LINE INDENT nodeStack . append ( node . left ) NEW_LINE DEDENT if ( pre != None ) : NEW_LINE INDENT pre . right = node NEW_LINE DEDENT pre = node NEW_LINE DEDENT DEDENT def printpre ( root ) : NEW_LINE INDENT while ( root != None ) : NEW_LINE INDENT print ( root . data , end = " ▁ " ) NEW_LINE root = root . right NEW_LINE DEDENT DEDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 8 ) NEW_LINE root . right = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE modifytree ( root ) NEW_LINE printpre ( root ) NEW_LINE
Check given array of size n can represent BST of n levels or not | A binary tree node has data , left child and right child ; To create a Tree with n levels . We always insert new node to left if it is less than previous value . ; Please refer below post for details of this function . www . geeksforgeeks . org / a - program - to - check - if - a - binary - tree - is - bst - or - not / https : ; Allow only distinct values ; Returns tree if given array of size n can represent a BST of n levels . ; Driver code
class newNode ( ) : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def createNLevelTree ( arr , n ) : NEW_LINE INDENT root = newNode ( arr [ 0 ] ) NEW_LINE temp = root NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( temp . key > arr [ i ] ) : NEW_LINE INDENT temp . left = newNode ( arr [ i ] ) NEW_LINE temp = temp . left NEW_LINE DEDENT else : NEW_LINE INDENT temp . right = newNode ( arr [ i ] ) NEW_LINE temp = temp . right NEW_LINE DEDENT DEDENT return root NEW_LINE DEDENT def isBST ( root , min , max ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root . key < min or root . key > max ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( isBST ( root . left , min , ( root . key ) - 1 ) and isBST ( root . right , ( root . key ) + 1 , max ) ) NEW_LINE DEDENT def canRepresentNLevelBST ( arr , n ) : NEW_LINE INDENT root = createNLevelTree ( arr , n ) NEW_LINE return isBST ( root , 0 , 2 ** 32 ) NEW_LINE DEDENT arr = [ 512 , 330 , 78 , 11 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE if ( canRepresentNLevelBST ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Check given array of size n can represent BST of n levels or not | Driver Code ; This element can be inserted to the right of the previous element , only if it is greater than the previous element and in the range . ; max remains same , update min ; This element can be inserted to the left of the previous element , only if it is lesser than the previous element and in the range . ; min remains same , update max ; if the loop completed successfully without encountering else condition
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5123 , 3300 , 783 , 1111 , 890 ] NEW_LINE n = len ( arr ) NEW_LINE max = 2147483647 NEW_LINE min = - 2147483648 NEW_LINE flag = True NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] and arr [ i ] > min and arr [ i ] < max ) : NEW_LINE INDENT min = arr [ i - 1 ] NEW_LINE DEDENT elif ( arr [ i ] < arr [ i - 1 ] and arr [ i ] > min and arr [ i ] < max ) : NEW_LINE INDENT max = arr [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Convert a normal BST to Balanced BST | Python3 program to convert a left unbalanced BST to a balanced BST ; A binary tree node has data , pointer to left child and a pointer to right child ; This function traverse the skewed binary tree and stores its nodes pointers in vector nodes [ ] ; Base case ; Store nodes in Inorder ( which is sorted order for BST ) ; Recursive function to construct binary tree ; base case ; Get the middle element and make it root ; Using index in Inorder traversal , construct left and right subtress ; This functions converts an unbalanced BST to a balanced BST ; Store nodes of given BST in sorted order ; Constucts BST from nodes [ ] ; Function to do preorder traversal of tree ; Driver code ; Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5
import sys NEW_LINE import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def storeBSTNodes ( root , nodes ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT storeBSTNodes ( root . left , nodes ) NEW_LINE nodes . append ( root ) NEW_LINE storeBSTNodes ( root . right , nodes ) NEW_LINE DEDENT def buildTreeUtil ( nodes , start , end ) : NEW_LINE INDENT if start > end : NEW_LINE INDENT return None NEW_LINE DEDENT mid = ( start + end ) // 2 NEW_LINE node = nodes [ mid ] NEW_LINE node . left = buildTreeUtil ( nodes , start , mid - 1 ) NEW_LINE node . right = buildTreeUtil ( nodes , mid + 1 , end ) NEW_LINE return node NEW_LINE DEDENT def buildTree ( root ) : NEW_LINE INDENT nodes = [ ] NEW_LINE storeBSTNodes ( root , nodes ) NEW_LINE n = len ( nodes ) NEW_LINE return buildTreeUtil ( nodes , 0 , n - 1 ) NEW_LINE DEDENT def preOrder ( root ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT print ( " { } ▁ " . format ( root . data ) , end = " " ) NEW_LINE preOrder ( root . left ) NEW_LINE preOrder ( root . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . left . left = Node ( 7 ) NEW_LINE root . left . left . left = Node ( 6 ) NEW_LINE root . left . left . left . left = Node ( 5 ) NEW_LINE root = buildTree ( root ) NEW_LINE print ( " Preorder ▁ traversal ▁ of ▁ balanced ▁ BST ▁ is ▁ : " ) NEW_LINE preOrder ( root ) NEW_LINE DEDENT
Find the node with minimum value in a Binary Search Tree | A binary tree node ; Give a binary search tree and a number , inserts a new node with the given number in the correct place in the tree . Returns the new root pointer which the caller should then use ( the standard trick to avoid using reference parameters ) . ; 1. If the tree is empty , return a new , single node ; 2. Otherwise , recur down the tree ; Return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the minimum data value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the lefmost leaf ; Driver program
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( node , data ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return ( Node ( data ) ) NEW_LINE DEDENT else : NEW_LINE INDENT if data <= node . data : NEW_LINE INDENT node . left = insert ( node . left , data ) NEW_LINE DEDENT else : NEW_LINE INDENT node . right = insert ( node . right , data ) NEW_LINE DEDENT return node NEW_LINE DEDENT DEDENT def minValue ( node ) : NEW_LINE INDENT current = node NEW_LINE while ( current . left is not None ) : NEW_LINE INDENT current = current . left NEW_LINE DEDENT return current . data NEW_LINE DEDENT root = None NEW_LINE root = insert ( root , 4 ) NEW_LINE insert ( root , 2 ) NEW_LINE insert ( root , 1 ) NEW_LINE insert ( root , 3 ) NEW_LINE insert ( root , 6 ) NEW_LINE insert ( root , 5 ) NEW_LINE print " NEW_LINE Minimum value in BST is % d " % ( minValue ( root ) ) NEW_LINE
Check if the given array can represent Level Order Traversal of Binary Search Tree | To store details of a node like node ' s ▁ ▁ data , ▁ ' min ' ▁ and ▁ ' max ' ▁ to ▁ obtain ▁ the ▁ ▁ range ▁ of ▁ values ▁ where ▁ node ' s left and right child 's should lie ; function to check if the given array can represent Level Order Traversal of Binary Search Tree ; if tree is empty ; queue to store NodeDetails ; index variable to access array elements ; node details for the root of the BST ; until there are no more elements in arr [ ] or queue is not empty ; extracting NodeDetails of a node from the queue ; check whether there are more elements in the arr [ ] and arr [ i ] can be left child of ' temp . data ' or not ; Create NodeDetails for newNode / and add it to the queue ; check whether there are more elements in the arr [ ] and arr [ i ] can be right child of ' temp . data ' or not ; Create NodeDetails for newNode / and add it to the queue ; given array represents level order traversal of BST ; given array do not represent level order traversal of BST ; Driver code
class NodeDetails : NEW_LINE INDENT def __init__ ( self , data , min , max ) : NEW_LINE INDENT self . data = data NEW_LINE self . min = min NEW_LINE self . max = max NEW_LINE DEDENT DEDENT def levelOrderIsOfBST ( arr , n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT q = [ ] NEW_LINE i = 0 NEW_LINE newNode = NodeDetails ( arr [ i ] , INT_MIN , INT_MAX ) NEW_LINE i += 1 NEW_LINE q . append ( newNode ) NEW_LINE while i != n and len ( q ) != 0 : NEW_LINE INDENT temp = q . pop ( 0 ) NEW_LINE if i < n and ( arr [ i ] < temp . data and arr [ i ] > temp . min ) : NEW_LINE INDENT newNode = NodeDetails ( arr [ i ] , temp . min , temp . data ) NEW_LINE i += 1 NEW_LINE q . append ( newNode ) NEW_LINE DEDENT if i < n and ( arr [ i ] > temp . data and arr [ i ] < temp . max ) : NEW_LINE INDENT newNode = NodeDetails ( arr [ i ] , temp . data , temp . max ) NEW_LINE i += 1 NEW_LINE q . append ( newNode ) NEW_LINE DEDENT DEDENT if i == n : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 4 , 12 , 3 , 6 , 8 , 1 , 5 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE if levelOrderIsOfBST ( arr , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Construct Tree from given Inorder and Preorder traversals | A binary tree node ; Recursive function to construct binary of size len from Inorder traversal in [ ] and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and len - 1. The function doesn 't do any error checking for cases where inorder and preorder do not form a tree ; Pich current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder Traversal , construct left and right subtrees ; Function to find index of value in arr [ start ... end ] The function assumes that value is rpesent in inOrder [ ] ; This funtcion is here just to test buildTree ( ) ; first recur on left child ; then print the data of node ; now recur on right child ; Driver program to test above function ; Let us test the build tree by priting Inorder traversal
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def buildTree ( inOrder , preOrder , inStrt , inEnd ) : NEW_LINE INDENT if ( inStrt > inEnd ) : NEW_LINE INDENT return None NEW_LINE DEDENT tNode = Node ( preOrder [ buildTree . preIndex ] ) NEW_LINE buildTree . preIndex += 1 NEW_LINE if inStrt == inEnd : NEW_LINE INDENT return tNode NEW_LINE DEDENT inIndex = search ( inOrder , inStrt , inEnd , tNode . data ) NEW_LINE tNode . left = buildTree ( inOrder , preOrder , inStrt , inIndex - 1 ) NEW_LINE tNode . right = buildTree ( inOrder , preOrder , inIndex + 1 , inEnd ) NEW_LINE return tNode NEW_LINE DEDENT def search ( arr , start , end , value ) : NEW_LINE INDENT for i in range ( start , end + 1 ) : NEW_LINE INDENT if arr [ i ] == value : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT DEDENT def printInorder ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( node . left ) NEW_LINE print node . data , NEW_LINE printInorder ( node . right ) NEW_LINE DEDENT inOrder = [ ' D ' , ' B ' , ' E ' , ' A ' , ' F ' , ' C ' ] NEW_LINE preOrder = [ ' A ' , ' B ' , ' D ' , ' E ' , ' C ' , ' F ' ] NEW_LINE buildTree . preIndex = 0 NEW_LINE root = buildTree ( inOrder , preOrder , 0 , len ( inOrder ) - 1 ) NEW_LINE print " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree ▁ is " NEW_LINE printInorder ( root ) NEW_LINE
Lowest Common Ancestor in a Binary Search Tree . | A recursive python program to find LCA of two nodes n1 and n2 A Binary tree node ; Function to find LCA of n1 and n2 . The function assumes that both n1 and n2 are present in BST ; If both n1 and n2 are smaller than root , then LCA lies in left ; If both n1 and n2 are greater than root , then LCA lies in right ; Let us construct the BST shown in the figure
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def lca ( root , n1 , n2 ) : NEW_LINE INDENT while root : NEW_LINE INDENT if root . data > n1 and root . data > n2 : NEW_LINE INDENT root = root . left NEW_LINE DEDENT elif root . data < n1 and root . data < n2 : NEW_LINE INDENT root = root . right NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return root NEW_LINE DEDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE n1 = 10 ; n2 = 14 NEW_LINE t = lca ( root , n1 , n2 ) NEW_LINE print " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d " % ( n1 , n2 , t . data ) NEW_LINE n1 = 14 ; n2 = 8 NEW_LINE t = lca ( root , n1 , n2 ) NEW_LINE print " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d " % ( n1 , n2 , t . data ) NEW_LINE n1 = 10 ; n2 = 22 NEW_LINE t = lca ( root , n1 , n2 ) NEW_LINE print " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d " % ( n1 , n2 , t . data ) NEW_LINE
A program to check if a binary tree is BST or not | ; Helper function that allocates a new node with the given data and None left and right poers . ; Returns true if given tree is BST . ; Base condition ; if left node exist then check it has correct data or not i . e . left node ' s ▁ data ▁ ▁ should ▁ be ▁ less ▁ than ▁ root ' s data ; if right node exist then check it has correct data or not i . e . right node ' s ▁ data ▁ ▁ should ▁ be ▁ greater ▁ than ▁ root ' s data ; check recursively for every node . ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isBST ( root , l = None , r = None ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( l != None and root . data <= l . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( r != None and root . data >= r . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT return isBST ( root . left , l , root ) and isBST ( root . right , root , r ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 3 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 1 ) NEW_LINE root . right . right = newNode ( 4 ) NEW_LINE if ( isBST ( root , None , None ) ) : NEW_LINE INDENT print ( " Is ▁ BST " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ a ▁ BST " ) NEW_LINE DEDENT DEDENT
A program to check if a binary tree is BST or not | Python3 program to check if a given tree is BST . ; A binary tree node has data , pointer to left child and a pointer to right child ; traverse the tree in inorder fashion and keep track of prev node ; Allows only distinct valued nodes ; Driver Code
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isBSTUtil ( root , prev ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT if ( isBSTUtil ( root . left , prev ) == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( prev != None and root . data <= prev . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT prev = root NEW_LINE return isBSTUtil ( root . right , prev ) NEW_LINE DEDENT return True NEW_LINE DEDENT def isBST ( root ) : NEW_LINE INDENT prev = None NEW_LINE return isBSTUtil ( root , prev ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 3 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 1 ) NEW_LINE root . right . right = Node ( 4 ) NEW_LINE if ( isBST ( root ) == None ) : NEW_LINE INDENT print ( " Is ▁ BST " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ a ▁ BST " ) NEW_LINE DEDENT DEDENT
Find k | A BST node ; Recursive function to insert an key into BST ; Function to find k 'th largest element in BST. Here count denotes the number of nodes processed so far ; Base case ; Search in left subtree ; If k 'th smallest is found in left subtree, return it ; If current element is k 'th smallest, return it ; Else search in right subtree ; Function to find k 'th largest element in BST ; Maintain index to count number of nodes processed so far ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return Node ( x ) NEW_LINE DEDENT if ( x < root . data ) : NEW_LINE INDENT root . left = insert ( root . left , x ) NEW_LINE DEDENT elif ( x > root . data ) : NEW_LINE INDENT root . right = insert ( root . right , x ) NEW_LINE DEDENT return root NEW_LINE DEDENT def kthSmallest ( root ) : NEW_LINE INDENT global k NEW_LINE if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT left = kthSmallest ( root . left ) NEW_LINE if ( left != None ) : NEW_LINE INDENT return left NEW_LINE DEDENT k -= 1 NEW_LINE if ( k == 0 ) : NEW_LINE INDENT return root NEW_LINE DEDENT return kthSmallest ( root . right ) NEW_LINE DEDENT def printKthSmallest ( root ) : NEW_LINE INDENT count = 0 NEW_LINE res = kthSmallest ( root ) NEW_LINE if ( res == None ) : NEW_LINE INDENT print ( " There ▁ are ▁ less ▁ than ▁ k ▁ nodes ▁ in ▁ the ▁ BST " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " K - th ▁ Smallest ▁ Element ▁ is ▁ " , res . data ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE keys = [ 20 , 8 , 22 , 4 , 12 , 10 , 14 ] NEW_LINE for x in keys : NEW_LINE INDENT root = insert ( root , x ) NEW_LINE DEDENT k = 3 NEW_LINE printKthSmallest ( root ) NEW_LINE DEDENT
Find k | A BST node ; Recursive function to insert an key into BST ; If a node is inserted in left subtree , then lCount of this node is increased . For simplicity , we are assuming that all keys ( tried to be inserted ) are distinct . ; Function to find k 'th largest element in BST. Here count denotes the number of nodes processed so far ; Base case ; Else search in right subtree ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . lCount = 0 NEW_LINE DEDENT DEDENT def insert ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return newNode ( x ) NEW_LINE DEDENT if ( x < root . data ) : NEW_LINE INDENT root . left = insert ( root . left , x ) NEW_LINE root . lCount += 1 NEW_LINE DEDENT elif ( x > root . data ) : NEW_LINE INDENT root . right = insert ( root . right , x ) ; NEW_LINE DEDENT return root NEW_LINE DEDENT def kthSmallest ( root , k ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT count = root . lCount + 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT return root NEW_LINE DEDENT if ( count > k ) : NEW_LINE INDENT return kthSmallest ( root . left , k ) NEW_LINE DEDENT return kthSmallest ( root . right , k - count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE keys = [ 20 , 8 , 22 , 4 , 12 , 10 , 14 ] NEW_LINE for x in keys : NEW_LINE INDENT root = insert ( root , x ) NEW_LINE DEDENT k = 4 NEW_LINE res = kthSmallest ( root , k ) NEW_LINE if ( res == None ) : NEW_LINE INDENT print ( " There ▁ are ▁ less ▁ than ▁ k ▁ nodes ▁ in ▁ the ▁ BST " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " K - th ▁ Smallest ▁ Element ▁ is " , res . data ) NEW_LINE DEDENT DEDENT
Construct Tree from given Inorder and Preorder traversals | A binary tree node has data , poer to left child and a poer to right child ; Recursive function to construct binary of size len from Inorder traversal in [ ] and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and len - 1. The function doesn 't do any error checking for cases where inorder and preorder do not form a tree ; Pick current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; This function mainly creates an unordered_map , then calls buildTree ( ) ; This funtcion is here just to test buildTree ( ) ; Driver code ; Let us test the built tree by pring Insorder traversal
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def buildTree ( inn , pre , inStrt , inEnd ) : NEW_LINE INDENT global preIndex , mp NEW_LINE if ( inStrt > inEnd ) : NEW_LINE INDENT return None NEW_LINE DEDENT curr = pre [ preIndex ] NEW_LINE preIndex += 1 NEW_LINE tNode = Node ( curr ) NEW_LINE if ( inStrt == inEnd ) : NEW_LINE INDENT return tNode NEW_LINE DEDENT inIndex = mp [ curr ] NEW_LINE tNode . left = buildTree ( inn , pre , inStrt , inIndex - 1 ) NEW_LINE tNode . right = buildTree ( inn , pre , inIndex + 1 , inEnd ) NEW_LINE return tNode NEW_LINE DEDENT def buldTreeWrap ( inn , pre , lenn ) : NEW_LINE INDENT global mp NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT mp [ inn [ i ] ] = i NEW_LINE DEDENT return buildTree ( inn , pre , 0 , lenn - 1 ) NEW_LINE DEDENT def prInorder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT prInorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE prInorder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mp = { } NEW_LINE preIndex = 0 NEW_LINE inn = [ ' D ' , ' B ' , ' E ' , ' A ' , ' F ' , ' C ' ] NEW_LINE pre = [ ' A ' , ' B ' , ' D ' , ' E ' , ' C ' , ' F ' ] NEW_LINE lenn = len ( inn ) NEW_LINE root = buldTreeWrap ( inn , pre , lenn ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ " " the ▁ constructed ▁ tree ▁ is " ) NEW_LINE prInorder ( root ) NEW_LINE DEDENT
Check if each internal node of a BST has exactly one child | Check if each internal node of BST has only one child ; driver program to test above function
def hasOnlyOneChild ( pre , size ) : NEW_LINE INDENT nextDiff = 0 ; lastDiff = 0 NEW_LINE for i in range ( size - 1 ) : NEW_LINE INDENT nextDiff = pre [ i ] - pre [ i + 1 ] NEW_LINE lastDiff = pre [ i ] - pre [ size - 1 ] NEW_LINE if nextDiff * lastDiff < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT pre = [ 8 , 3 , 5 , 7 , 6 ] NEW_LINE size = len ( pre ) NEW_LINE if ( hasOnlyOneChild ( pre , size ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Check if each internal node of a BST has exactly one child | Check if each internal node of BST has only one child approach 2 ; Initialize min and max using last two elements ; Every element must be either smaller than min or greater than max ; Driver program to test above function
def hasOnlyOneChild ( pre , size ) : NEW_LINE INDENT min = 0 ; max = 0 NEW_LINE if pre [ size - 1 ] > pre [ size - 2 ] : NEW_LINE INDENT max = pre [ size - 1 ] NEW_LINE min = pre [ size - 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT max = pre [ size - 2 ] NEW_LINE min = pre [ size - 1 ] NEW_LINE DEDENT for i in range ( size - 3 , 0 , - 1 ) : NEW_LINE INDENT if pre [ i ] < min : NEW_LINE INDENT min = pre [ i ] NEW_LINE DEDENT elif pre [ i ] > max : NEW_LINE INDENT max = pre [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT pre = [ 8 , 3 , 5 , 7 , 6 ] NEW_LINE size = len ( pre ) NEW_LINE if ( hasOnlyOneChild ( pre , size ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
K 'th smallest element in BST using O(1) Extra Space | A BST node ; A function to find ; Count to iterate over elements till we get the kth smallest number ; store the Kth smallest ; to store the current node ; Like Morris traversal if current does not have left child rather than printing as we did in inorder , we will just increment the count as the number will be in an increasing order ; if count is equal to K then we found the kth smallest , so store it in ksmall ; go to current 's right child ; we create links to Inorder Successor and count using these links ; building links ; link made to Inorder Successor ; While breaking the links in so made temporary threaded tree we will check for the K smallest condition ; Revert the changes made in if part ( break link from the Inorder Successor ) ; If count is equal to K then we found the kth smallest and so store it in ksmall ; return the found value ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Driver Code ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def KSmallestUsingMorris ( root , k ) : NEW_LINE INDENT count = 0 NEW_LINE ksmall = - 9999999999 NEW_LINE curr = root NEW_LINE while curr != None : NEW_LINE INDENT if curr . left == None : NEW_LINE INDENT count += 1 NEW_LINE if count == k : NEW_LINE INDENT ksmall = curr . key NEW_LINE DEDENT curr = curr . right NEW_LINE DEDENT else : NEW_LINE INDENT pre = curr . left NEW_LINE while ( pre . right != None and pre . right != curr ) : NEW_LINE INDENT pre = pre . right NEW_LINE DEDENT if pre . right == None : NEW_LINE INDENT pre . right = curr NEW_LINE curr = curr . left NEW_LINE DEDENT else : NEW_LINE INDENT pre . right = None NEW_LINE count += 1 NEW_LINE if count == k : NEW_LINE INDENT ksmall = curr . key NEW_LINE DEDENT curr = curr . right NEW_LINE DEDENT DEDENT DEDENT return ksmall NEW_LINE DEDENT def insert ( node , key ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return Node ( key ) NEW_LINE DEDENT if key < node . key : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT elif key > node . key : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 50 ) NEW_LINE insert ( root , 30 ) NEW_LINE insert ( root , 20 ) NEW_LINE insert ( root , 40 ) NEW_LINE insert ( root , 70 ) NEW_LINE insert ( root , 60 ) NEW_LINE insert ( root , 80 ) NEW_LINE for k in range ( 1 , 8 ) : NEW_LINE INDENT print ( KSmallestUsingMorris ( root , k ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Check if given sorted sub | Constructor to create a new node ; A utility function to insert a given key to BST ; function to check if given sorted sub - sequence exist in BST index . iterator for given sorted sub - sequence seq [ ] . given sorted sub - sequence ; We traverse left subtree first in Inorder ; If current node matches with se [ index [ 0 ] ] then move forward in sub - sequence ; We traverse left subtree in the end in Inorder ; A wrapper over seqExistUtil . It returns true if seq [ 0. . n - 1 ] exists in tree . ; Initialize index in seq [ ] ; Do an inorder traversal and find if all elements of seq [ ] were present ; index would become n if all elements of seq [ ] were present ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return Node ( key ) NEW_LINE DEDENT if root . data > key : NEW_LINE INDENT root . left = insert ( root . left , key ) NEW_LINE DEDENT else : NEW_LINE INDENT root . right = insert ( root . right , key ) NEW_LINE DEDENT return root NEW_LINE DEDENT def seqExistUtil ( ptr , seq , index ) : NEW_LINE INDENT if ptr == None : NEW_LINE INDENT return NEW_LINE DEDENT seqExistUtil ( ptr . left , seq , index ) NEW_LINE if ptr . data == seq [ index [ 0 ] ] : NEW_LINE INDENT index [ 0 ] += 1 NEW_LINE DEDENT seqExistUtil ( ptr . right , seq , index ) NEW_LINE DEDENT def seqExist ( root , seq , n ) : NEW_LINE INDENT index = [ 0 ] NEW_LINE seqExistUtil ( root , seq , index ) NEW_LINE if index [ 0 ] == n : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 8 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE root = insert ( root , 3 ) NEW_LINE root = insert ( root , 6 ) NEW_LINE root = insert ( root , 1 ) NEW_LINE root = insert ( root , 4 ) NEW_LINE root = insert ( root , 7 ) NEW_LINE root = insert ( root , 14 ) NEW_LINE root = insert ( root , 13 ) NEW_LINE seq = [ 4 , 6 , 8 , 14 ] NEW_LINE n = len ( seq ) NEW_LINE if seqExist ( root , seq , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Check if an array represents Inorder of Binary Search tree or not | Function that returns true if array is Inorder traversal of any Binary Search Tree or not . ; Array has one or no element ; Unsorted pair found ; No unsorted pair found ; Driver code
def isInorder ( arr , n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] > arr [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 19 , 23 , 25 , 30 , 45 ] NEW_LINE n = len ( arr ) NEW_LINE if ( isInorder ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Construct Tree from given Inorder and Preorder traversals | Python3 program to construct a tree using inorder and preorder traversal ; Function to build tree using given traversal ; Function to prtree in_t Inorder ; first recur on left child ; then prthe data of node ; now recur on right child ; Driver code
class TreeNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . val = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT s = set ( ) NEW_LINE st = [ ] NEW_LINE def buildTree ( preorder , inorder , n ) : NEW_LINE INDENT root = None ; NEW_LINE pre = 0 NEW_LINE in_t = 0 NEW_LINE while pre < n : NEW_LINE INDENT node = None ; NEW_LINE while True : NEW_LINE INDENT node = TreeNode ( preorder [ pre ] ) NEW_LINE if ( root == None ) : NEW_LINE INDENT root = node ; NEW_LINE DEDENT if ( len ( st ) > 0 ) : NEW_LINE INDENT if ( st [ - 1 ] in s ) : NEW_LINE INDENT s . discard ( st [ - 1 ] ) ; NEW_LINE st [ - 1 ] . right = node ; NEW_LINE st . pop ( ) ; NEW_LINE DEDENT else : NEW_LINE INDENT st [ - 1 ] . left = node ; NEW_LINE DEDENT DEDENT st . append ( node ) ; NEW_LINE if pre >= n or preorder [ pre ] == inorder [ in_t ] : NEW_LINE INDENT pre += 1 NEW_LINE break NEW_LINE DEDENT pre += 1 NEW_LINE DEDENT node = None ; NEW_LINE while ( len ( st ) > 0 and in_t < n and st [ - 1 ] . val == inorder [ in_t ] ) : NEW_LINE INDENT node = st [ - 1 ] ; NEW_LINE st . pop ( ) ; NEW_LINE in_t += 1 NEW_LINE DEDENT if ( node != None ) : NEW_LINE INDENT s . add ( node ) ; NEW_LINE st . append ( node ) ; NEW_LINE DEDENT DEDENT return root ; NEW_LINE DEDENT def printInorder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT printInorder ( node . left ) ; NEW_LINE print ( node . val , end = " ▁ " ) ; NEW_LINE printInorder ( node . right ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT in_t = [ 9 , 8 , 4 , 2 , 10 , 5 , 10 , 1 , 6 , 3 , 13 , 12 , 7 ] NEW_LINE pre = [ 1 , 2 , 4 , 8 , 9 , 5 , 10 , 10 , 3 , 6 , 7 , 12 , 13 ] NEW_LINE l = len ( in_t ) NEW_LINE root = buildTree ( pre , in_t , l ) ; NEW_LINE printInorder ( root ) ; NEW_LINE DEDENT
Check if two BSTs contain same set of elements | BST Node ; Utility function to create Node ; function to insert elements of the tree to map m ; function to check if the two BSTs contain same set of elements ; Base cases ; Create two hash sets and store elements both BSTs in them . ; Return True if both hash sets contain same elements . ; First BST ; Second BST ; check if two BSTs have same set of elements
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . val = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def Node_ ( val1 ) : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . val = val1 NEW_LINE temp . left = temp . right = None NEW_LINE return temp NEW_LINE DEDENT s = { } NEW_LINE def insertToHash ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT insertToHash ( root . left ) NEW_LINE s . add ( root . data ) NEW_LINE insertToHash ( root . right ) NEW_LINE DEDENT def checkBSTs ( root1 , root2 ) : NEW_LINE INDENT if ( root1 != None and root2 != None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( root1 == None and root2 != None ) or ( root1 != None and root2 == None ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT s1 = { } NEW_LINE s2 = { } NEW_LINE s = s1 NEW_LINE insertToHash ( root1 ) NEW_LINE s1 = s NEW_LINE s = s2 NEW_LINE insertToHash ( root2 ) NEW_LINE s2 = s NEW_LINE return ( s1 == ( s2 ) ) NEW_LINE DEDENT root1 = Node_ ( 15 ) NEW_LINE root1 . left = Node_ ( 10 ) NEW_LINE root1 . right = Node_ ( 20 ) NEW_LINE root1 . left . left = Node_ ( 5 ) NEW_LINE root1 . left . right = Node_ ( 12 ) NEW_LINE root1 . right . right = Node_ ( 25 ) NEW_LINE root2 = Node_ ( 15 ) NEW_LINE root2 . left = Node_ ( 12 ) NEW_LINE root2 . right = Node_ ( 20 ) NEW_LINE root2 . left . left = Node_ ( 5 ) NEW_LINE root2 . left . left . right = Node_ ( 10 ) NEW_LINE root2 . right . right = Node_ ( 25 ) NEW_LINE if ( checkBSTs ( root1 , root2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Check if two BSTs contain same set of elements | BST Node ; Utility function to create Node ; function to insert elements of the tree to map m ; function to check if the two BSTs contain same set of elements ; Base cases ; Create two hash sets and store elements both BSTs in them . ; Return True if both hash sets contain same elements . ; First BST ; Second BST ; check if two BSTs have same set of elements
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . val = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def Node_ ( val1 ) : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . val = val1 NEW_LINE temp . left = temp . right = None NEW_LINE return temp NEW_LINE DEDENT v = [ ] NEW_LINE def storeInorder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT storeInorder ( root . left ) NEW_LINE v . append ( root . data ) NEW_LINE storeInorder ( root . right ) NEW_LINE DEDENT def checkBSTs ( root1 , root2 ) : NEW_LINE INDENT if ( root1 != None and root2 != None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( root1 == None and root2 != None ) or ( root1 != None and root2 == None ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE v = v1 NEW_LINE storeInorder ( root1 ) NEW_LINE v1 = v NEW_LINE v = v2 NEW_LINE storeInorder ( root2 ) NEW_LINE v2 = v NEW_LINE return ( v1 == v2 ) NEW_LINE DEDENT root1 = Node_ ( 15 ) NEW_LINE root1 . left = Node_ ( 10 ) NEW_LINE root1 . right = Node_ ( 20 ) NEW_LINE root1 . left . left = Node_ ( 5 ) NEW_LINE root1 . left . right = Node_ ( 12 ) NEW_LINE root1 . right . right = Node_ ( 25 ) NEW_LINE root2 = Node_ ( 15 ) NEW_LINE root2 . left = Node_ ( 12 ) NEW_LINE root2 . right = Node_ ( 20 ) NEW_LINE root2 . left . left = Node_ ( 5 ) NEW_LINE root2 . left . left . right = Node_ ( 10 ) NEW_LINE root2 . right . right = Node_ ( 25 ) NEW_LINE if ( checkBSTs ( root1 , root2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Shortest distance between two nodes in BST | Python3 program to find distance between two nodes in BST ; Standard BST insert function ; This function returns distance of x from root . This function assumes that x exists in BST and BST is not NULL . ; Returns minimum distance beween a and b . This function assumes that a and b exist in BST . ; Both keys lie in left ; Both keys lie in right same path ; Lie in opposite directions ( Root is LCA of two nodes ) ; This function make sure that a is smaller than b before making a call to findDistWrapper ( ) ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT root = newNode ( key ) NEW_LINE DEDENT elif root . key > key : NEW_LINE INDENT root . left = insert ( root . left , key ) NEW_LINE DEDENT elif root . key < key : NEW_LINE INDENT root . right = insert ( root . right , key ) NEW_LINE DEDENT return root NEW_LINE DEDENT def distanceFromRoot ( root , x ) : NEW_LINE INDENT if root . key == x : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif root . key > x : NEW_LINE INDENT return 1 + distanceFromRoot ( root . left , x ) NEW_LINE DEDENT return 1 + distanceFromRoot ( root . right , x ) NEW_LINE DEDENT def distanceBetween2 ( root , a , b ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root . key > a and root . key > b : NEW_LINE INDENT return distanceBetween2 ( root . left , a , b ) NEW_LINE DEDENT if root . key < a and root . key < b : NEW_LINE INDENT return distanceBetween2 ( root . right , a , b ) NEW_LINE DEDENT if root . key >= a and root . key <= b : NEW_LINE INDENT return ( distanceFromRoot ( root , a ) + distanceFromRoot ( root , b ) ) NEW_LINE DEDENT DEDENT def findDistWrapper ( root , a , b ) : NEW_LINE INDENT if a > b : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT return distanceBetween2 ( root , a , b ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 20 ) NEW_LINE insert ( root , 10 ) NEW_LINE insert ( root , 5 ) NEW_LINE insert ( root , 15 ) NEW_LINE insert ( root , 30 ) NEW_LINE insert ( root , 25 ) NEW_LINE insert ( root , 35 ) NEW_LINE a , b = 5 , 55 NEW_LINE print ( findDistWrapper ( root , 5 , 35 ) ) NEW_LINE DEDENT
Print BST keys in given Range | O ( 1 ) Space | Python3 code to print BST keys in given Range in constant space using Morris traversal . Helper function to create a new node ; Function to print the keys in range ; check if current node lies between n1 and n2 ; finding the inorder predecessor - inorder predecessor is the right most in left subtree or the left child , i . e in BST it is the maximum ( right most ) in left subtree . ; check if current node lies between n1 and n2 ; Driver Code ; Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def RangeTraversal ( root , n1 , n2 ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT curr = root NEW_LINE while curr : NEW_LINE INDENT if curr . left == None : NEW_LINE INDENT if curr . data <= n2 and curr . data >= n1 : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE DEDENT curr = curr . right NEW_LINE DEDENT else : NEW_LINE INDENT pre = curr . left NEW_LINE while ( pre . right != None and pre . right != curr ) : NEW_LINE INDENT pre = pre . right NEW_LINE DEDENT if pre . right == None : NEW_LINE INDENT pre . right = curr ; NEW_LINE curr = curr . left NEW_LINE DEDENT else : NEW_LINE INDENT pre . right = None NEW_LINE if curr . data <= n2 and curr . data >= n1 : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE DEDENT curr = curr . right NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 4 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 7 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 10 ) NEW_LINE RangeTraversal ( root , 4 , 12 ) NEW_LINE DEDENT
Count BST subtrees that lie in given range | A utility function to check if data of root is in range from low to high ; A recursive function to get count of nodes whose subtree is in range from low to high . This function returns true if nodes in subtree rooted under ' root ' are in range . ; Base case ; Recur for left and right subtrees ; If both left and right subtrees are in range and current node is also in range , then increment count and return true ; A wrapper over getCountUtil ( ) . This function initializes count as 0 and calls getCountUtil ( ) ; Utility function to create new node ; Driver Code ; Let us construct the BST shown in the above figure ; Let us constructed BST shown in above example 10 / \ 5 50 / / \ 1 40 100
def inRange ( root , low , high ) : NEW_LINE INDENT return root . data >= low and root . data <= high NEW_LINE DEDENT def getCountUtil ( root , low , high , count ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return True NEW_LINE DEDENT l = getCountUtil ( root . left , low , high , count ) NEW_LINE r = getCountUtil ( root . right , low , high , count ) NEW_LINE if l and r and inRange ( root , low , high ) : NEW_LINE INDENT count [ 0 ] += 1 NEW_LINE return True NEW_LINE DEDENT return False NEW_LINE DEDENT def getCount ( root , low , high ) : NEW_LINE INDENT count = [ 0 ] NEW_LINE getCountUtil ( root , low , high , count ) NEW_LINE return count NEW_LINE DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 5 ) NEW_LINE root . right = newNode ( 50 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . right . left = newNode ( 40 ) NEW_LINE root . right . right = newNode ( 100 ) NEW_LINE l = 5 NEW_LINE h = 45 NEW_LINE print ( " Count ▁ of ▁ subtrees ▁ in ▁ [ " , l , " , ▁ " , h , " ] ▁ is ▁ " , getCount ( root , l , h ) ) NEW_LINE DEDENT
Remove all leaf nodes from the binary search tree | Python 3 program to delete leaf Node from binary search tree . Create a newNode in binary search tree . ; Constructor to create a new node ; Insert a Node in binary search tree . ; Function for inorder traversal in a BST . ; Delete leaf nodes from binary search tree . ; Else recursively delete in left and right subtrees . ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , data ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return newNode ( data ) NEW_LINE DEDENT if data < root . data : NEW_LINE INDENT root . left = insert ( root . left , data ) NEW_LINE DEDENT elif data > root . data : NEW_LINE INDENT root . right = insert ( root . right , data ) NEW_LINE DEDENT return root NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if root != None : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT def leafDelete ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . left == None and root . right == None : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = leafDelete ( root . left ) NEW_LINE root . right = leafDelete ( root . right ) NEW_LINE return root NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 20 ) NEW_LINE insert ( root , 10 ) NEW_LINE insert ( root , 5 ) NEW_LINE insert ( root , 15 ) NEW_LINE insert ( root , 30 ) NEW_LINE insert ( root , 25 ) NEW_LINE insert ( root , 35 ) NEW_LINE print ( " Inorder ▁ before ▁ Deleting ▁ the ▁ leaf ▁ Node . " ) NEW_LINE inorder ( root ) NEW_LINE leafDelete ( root ) NEW_LINE print ( ) NEW_LINE print ( " INorder ▁ after ▁ Deleting ▁ the ▁ leaf ▁ Node . " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT
Sum of k smallest elements in BST | Python3 program to find Sum Of All Elements smaller than or equal to Kth Smallest Element In BST ; utility that allocates a newNode with the given key ; A utility function to insert a new Node with given key in BST and also maintain lcount , Sum ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; return the ( unchanged ) Node pointer ; function return sum of all element smaller than and equal to Kth smallest element ; Base cases ; Compute sum of elements in left subtree ; Add root 's data ; Add current Node ; If count is less than k , return right subtree Nodes ; Wrapper over ksmallestElementSumRec ( ) ; Driver Code ; 20 / \ 8 22 / \ 4 12 / \ 10 14
INT_MAX = 2147483647 NEW_LINE class createNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , key ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return createNode ( key ) NEW_LINE DEDENT if ( root . data > key ) : NEW_LINE INDENT root . left = insert ( root . left , key ) NEW_LINE DEDENT elif ( root . data < key ) : NEW_LINE INDENT root . right = insert ( root . right , key ) NEW_LINE DEDENT return root NEW_LINE DEDENT def ksmallestElementSumRec ( root , k , count ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( count [ 0 ] > k [ 0 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = ksmallestElementSumRec ( root . left , k , count ) NEW_LINE if ( count [ 0 ] >= k [ 0 ] ) : NEW_LINE INDENT return res NEW_LINE DEDENT res += root . data NEW_LINE count [ 0 ] += 1 NEW_LINE if ( count [ 0 ] >= k [ 0 ] ) : NEW_LINE INDENT return res NEW_LINE DEDENT return res + ksmallestElementSumRec ( root . right , k , count ) NEW_LINE DEDENT def ksmallestElementSum ( root , k ) : NEW_LINE INDENT count = [ 0 ] NEW_LINE return ksmallestElementSumRec ( root , k , count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 20 ) NEW_LINE root = insert ( root , 8 ) NEW_LINE root = insert ( root , 4 ) NEW_LINE root = insert ( root , 12 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE root = insert ( root , 14 ) NEW_LINE root = insert ( root , 22 ) NEW_LINE k = [ 3 ] NEW_LINE print ( ksmallestElementSum ( root , k ) ) NEW_LINE DEDENT
Sum of k smallest elements in BST | utility function new Node of BST ; A utility function to insert a new Node with given key in BST and also maintain lcount , Sum ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; increment lCount of current Node ; increment current Node sum by adding key into it ; return the ( unchanged ) Node pointer ; function return sum of all element smaller than and equal to Kth smallest element ; if we fount k smallest element then break the function ; store sum of all element smaller than current root ; ; decremented k and call right sub - tree ; call left sub - tree ; Wrapper over ksmallestElementSumRec ( ) ; Driver Code ; 20 / \ 8 22 / \ 4 12 / \ 10 14
class createNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . lCount = 0 NEW_LINE self . Sum = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return createNode ( key ) NEW_LINE DEDENT if root . data > key : NEW_LINE INDENT root . lCount += 1 NEW_LINE root . Sum += key NEW_LINE root . left = insert ( root . left , key ) NEW_LINE DEDENT elif root . data < key : NEW_LINE INDENT root . right = insert ( root . right , key ) NEW_LINE DEDENT return root NEW_LINE DEDENT def ksmallestElementSumRec ( root , k , temp_sum ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . lCount + 1 ) == k : NEW_LINE INDENT temp_sum [ 0 ] += root . data + root . Sum NEW_LINE return NEW_LINE DEDENT elif k > root . lCount : NEW_LINE INDENT temp_sum [ 0 ] += root . data + root . Sum NEW_LINE k = k - ( root . lCount + 1 ) NEW_LINE ksmallestElementSumRec ( root . right , k , temp_sum ) NEW_LINE DEDENT else : NEW_LINE INDENT ksmallestElementSumRec ( root . left , k , temp_sum ) NEW_LINE DEDENT DEDENT def ksmallestElementSum ( root , k ) : NEW_LINE INDENT Sum = [ 0 ] NEW_LINE ksmallestElementSumRec ( root , k , Sum ) NEW_LINE return Sum [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 20 ) NEW_LINE root = insert ( root , 8 ) NEW_LINE root = insert ( root , 4 ) NEW_LINE root = insert ( root , 12 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE root = insert ( root , 14 ) NEW_LINE root = insert ( root , 22 ) NEW_LINE k = 3 NEW_LINE print ( ksmallestElementSum ( root , k ) ) NEW_LINE DEDENT
Inorder Successor in Binary Search Tree | A binary tree node ; Given a binary search tree and a number , inserts a new node with the given number in the correct place in the tree . Returns the new root pointer which the caller should then use ( the standard trick to avoidusing reference parameters ) ; 1 ) If tree is empty then return a new singly node ; 2 ) Otherwise , recur down the tree ; return the unchanged node pointer ; Step 1 of the above algorithm ; Step 2 of the above algorithm ; Given a non - empty binary search tree , return the minimum data value found in that tree . Note that the entire tree doesn 't need to be searched ; loop down to find the leftmost leaf ; Driver progam to test above function
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( node , data ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return Node ( data ) NEW_LINE DEDENT else : NEW_LINE INDENT if data <= node . data : NEW_LINE INDENT temp = insert ( node . left , data ) NEW_LINE node . left = temp NEW_LINE temp . parent = node NEW_LINE DEDENT else : NEW_LINE INDENT temp = insert ( node . right , data ) NEW_LINE node . right = temp NEW_LINE temp . parent = node NEW_LINE DEDENT return node NEW_LINE DEDENT DEDENT def inOrderSuccessor ( n ) : NEW_LINE INDENT if n . right is not None : NEW_LINE INDENT return minValue ( n . right ) NEW_LINE DEDENT p = n . parent NEW_LINE while ( p is not None ) : NEW_LINE INDENT if n != p . right : NEW_LINE INDENT break NEW_LINE DEDENT n = p NEW_LINE p = p . parent NEW_LINE DEDENT return p NEW_LINE DEDENT def minValue ( node ) : NEW_LINE INDENT current = node NEW_LINE while ( current is not None ) : NEW_LINE INDENT if current . left is None : NEW_LINE INDENT break NEW_LINE DEDENT current = current . left NEW_LINE DEDENT return current NEW_LINE DEDENT root = None NEW_LINE root = insert ( root , 20 ) NEW_LINE root = insert ( root , 8 ) ; NEW_LINE root = insert ( root , 22 ) ; NEW_LINE root = insert ( root , 4 ) ; NEW_LINE root = insert ( root , 12 ) ; NEW_LINE root = insert ( root , 10 ) ; NEW_LINE root = insert ( root , 14 ) ; NEW_LINE temp = root . left . right . right NEW_LINE succ = inOrderSuccessor ( root , temp ) NEW_LINE if succ is not None : NEW_LINE INDENT print " \n Inorder ▁ Successor ▁ of ▁ % ▁ d ▁ is ▁ % ▁ d ▁ " % ( temp . data , succ . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print " \n Inorder ▁ Successor ▁ doesn ' t ▁ exist " NEW_LINE DEDENT
Inorder predecessor and successor for a given key in BST | A Binary Tree Node Utility function to create a new tree node ; since inorder traversal results in ascendingorder visit to node , we can store the values of the largest o which is smaller than a ( predecessor ) and smallest no which is large than a ( successor ) using inorder traversal ; If root is None return ; traverse the left subtree ; root data is greater than a ; q stores the node whose data is greater than a and is smaller than the previously stored data in * q which is successor ; if the root data is smaller than store it in p which is predecessor ; traverse the right subtree ; Driver Code
class getnode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def find_p_s ( root , a , p , q ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT find_p_s ( root . left , a , p , q ) NEW_LINE if ( root and root . data > a ) : NEW_LINE INDENT if ( ( not q [ 0 ] ) or q [ 0 ] and q [ 0 ] . data > root . data ) : NEW_LINE INDENT q [ 0 ] = root NEW_LINE DEDENT DEDENT elif ( root and root . data < a ) : NEW_LINE INDENT p [ 0 ] = root NEW_LINE DEDENT find_p_s ( root . right , a , p , q ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = getnode ( 50 ) NEW_LINE root1 . left = getnode ( 20 ) NEW_LINE root1 . right = getnode ( 60 ) NEW_LINE root1 . left . left = getnode ( 10 ) NEW_LINE root1 . left . right = getnode ( 30 ) NEW_LINE root1 . right . left = getnode ( 55 ) NEW_LINE root1 . right . right = getnode ( 70 ) NEW_LINE p = [ None ] NEW_LINE q = [ None ] NEW_LINE find_p_s ( root1 , 55 , p , q ) NEW_LINE if ( p [ 0 ] ) : NEW_LINE INDENT print ( p [ 0 ] . data , end = " " ) NEW_LINE DEDENT if ( q [ 0 ] ) : NEW_LINE INDENT print ( " " , q [ 0 ] . data ) NEW_LINE DEDENT DEDENT
Inorder predecessor and successor for a given key in BST | Iterative Approach | Function that finds predecessor and successor of key in BST . ; Search for given key in BST . ; If root is given key . ; the minimum value in right subtree is predecessor . ; the maximum value in left subtree is successor . ; If key is greater than root , then key lies in right subtree . Root could be predecessor if left subtree of key is null . ; If key is smaller than root , then key lies in left subtree . Root could be successor if right subtree of key is null . ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; Driver Code ; Key to be searched in BST ; Let us create following BST 50 / \ / \ 30 70 / \ / \ / \ / \ 20 40 60 80
def findPreSuc ( root , pre , suc , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT while root != None : NEW_LINE INDENT if root . key == key : NEW_LINE INDENT if root . right : NEW_LINE INDENT suc [ 0 ] = root . right NEW_LINE while suc [ 0 ] . left : NEW_LINE INDENT suc [ 0 ] = suc [ 0 ] . left NEW_LINE DEDENT DEDENT if root . left : NEW_LINE INDENT pre [ 0 ] = root . left NEW_LINE while pre [ 0 ] . right : NEW_LINE INDENT pre [ 0 ] = pre [ 0 ] . right NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT elif root . key < key : NEW_LINE INDENT pre [ 0 ] = root NEW_LINE root = root . right NEW_LINE DEDENT else : NEW_LINE INDENT suc [ 0 ] = root NEW_LINE root = root . left NEW_LINE DEDENT DEDENT DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if key < node . key : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT else : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT key = 65 NEW_LINE root = None NEW_LINE root = insert ( root , 50 ) NEW_LINE insert ( root , 30 ) NEW_LINE insert ( root , 20 ) NEW_LINE insert ( root , 40 ) NEW_LINE insert ( root , 70 ) NEW_LINE insert ( root , 60 ) NEW_LINE insert ( root , 80 ) NEW_LINE pre , suc = [ None ] , [ None ] NEW_LINE findPreSuc ( root , pre , suc , key ) NEW_LINE if pre [ 0 ] != None : NEW_LINE INDENT print ( " Predecessor ▁ is " , pre [ 0 ] . key ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT if suc [ 0 ] != None : NEW_LINE INDENT print ( " Successor ▁ is " , suc [ 0 ] . key ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT
Find a pair with given sum in BST | Python3 program to find a pair with given sum using hashing ; Driver code
import sys NEW_LINE import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , data ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return Node ( data ) NEW_LINE DEDENT if ( data < root . data ) : NEW_LINE INDENT root . left = insert ( root . left , data ) NEW_LINE DEDENT if ( data > root . data ) : NEW_LINE INDENT root . right = insert ( root . right , data ) NEW_LINE DEDENT return root NEW_LINE DEDENT def findPairUtil ( root , summ , unsorted_set ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return False NEW_LINE DEDENT if findPairUtil ( root . left , summ , unsorted_set ) : NEW_LINE INDENT return True NEW_LINE DEDENT if unsorted_set and ( summ - root . data ) in unsorted_set : NEW_LINE INDENT print ( " Pair ▁ is ▁ Found ▁ ( { } , { } ) " . format ( summ - root . data , root . data ) ) NEW_LINE return True NEW_LINE DEDENT else : NEW_LINE INDENT unsorted_set . add ( root . data ) NEW_LINE DEDENT return findPairUtil ( root . right , summ , unsorted_set ) NEW_LINE DEDENT def findPair ( root , summ ) : NEW_LINE INDENT unsorted_set = set ( ) NEW_LINE if ( not findPairUtil ( root , summ , unsorted_set ) ) : NEW_LINE INDENT print ( " Pair ▁ do ▁ not ▁ exist ! " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 15 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE root = insert ( root , 20 ) NEW_LINE root = insert ( root , 8 ) NEW_LINE root = insert ( root , 12 ) NEW_LINE root = insert ( root , 16 ) NEW_LINE root = insert ( root , 25 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE summ = 33 NEW_LINE findPair ( root , summ ) NEW_LINE DEDENT
Find pairs with given sum such that pair elements lie in different BSTs | A utility function to create a new BST node with key as given num ; Constructor to create a new node ; A utility function to insert a given key to BST ; store storeInorder traversal in auxiliary array ; Function to find pair for given sum in different bst vect1 [ ] -- > stores storeInorder traversal of first bst vect2 [ ] -- > stores storeInorder traversal of second bst ; Initialize two indexes to two different corners of two lists . ; find pair by moving two corners . ; If we found a pair ; If sum is more , move to higher value in first lists . ; If sum is less , move to lower value in second lists . ; Prints all pairs with given " sum " such that one element of pair is in tree with root1 and other node is in tree with root2 . ; Store inorder traversals of two BSTs in two lists . ; Now the problem reduces to finding a pair with given sum such that one element is in vect1 and other is in vect2 . ; Driver Code ; first BST ; second BST
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if root . data > key : NEW_LINE INDENT root . left = insert ( root . left , key ) NEW_LINE DEDENT else : NEW_LINE INDENT root . right = insert ( root . right , key ) NEW_LINE DEDENT return root NEW_LINE DEDENT def storeInorder ( ptr , vect ) : NEW_LINE INDENT if ptr == None : NEW_LINE INDENT return NEW_LINE DEDENT storeInorder ( ptr . left , vect ) NEW_LINE vect . append ( ptr . data ) NEW_LINE storeInorder ( ptr . right , vect ) NEW_LINE DEDENT def pairSumUtil ( vect1 , vect2 , Sum ) : NEW_LINE INDENT left = 0 NEW_LINE right = len ( vect2 ) - 1 NEW_LINE while left < len ( vect1 ) and right >= 0 : NEW_LINE INDENT if vect1 [ left ] + vect2 [ right ] == Sum : NEW_LINE INDENT print ( " ( " , vect1 [ left ] , " , " , vect2 [ right ] , " ) , " , end = " ▁ " ) NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT elif vect1 [ left ] + vect2 [ right ] < Sum : NEW_LINE INDENT left += 1 NEW_LINE DEDENT else : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT DEDENT DEDENT def pairSum ( root1 , root2 , Sum ) : NEW_LINE INDENT vect1 = [ ] NEW_LINE vect2 = [ ] NEW_LINE storeInorder ( root1 , vect1 ) NEW_LINE storeInorder ( root2 , vect2 ) NEW_LINE pairSumUtil ( vect1 , vect2 , Sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = None NEW_LINE root1 = insert ( root1 , 8 ) NEW_LINE root1 = insert ( root1 , 10 ) NEW_LINE root1 = insert ( root1 , 3 ) NEW_LINE root1 = insert ( root1 , 6 ) NEW_LINE root1 = insert ( root1 , 1 ) NEW_LINE root1 = insert ( root1 , 5 ) NEW_LINE root1 = insert ( root1 , 7 ) NEW_LINE root1 = insert ( root1 , 14 ) NEW_LINE root1 = insert ( root1 , 13 ) NEW_LINE root2 = None NEW_LINE root2 = insert ( root2 , 5 ) NEW_LINE root2 = insert ( root2 , 18 ) NEW_LINE root2 = insert ( root2 , 2 ) NEW_LINE root2 = insert ( root2 , 1 ) NEW_LINE root2 = insert ( root2 , 3 ) NEW_LINE root2 = insert ( root2 , 4 ) NEW_LINE Sum = 10 NEW_LINE pairSum ( root1 , root2 , Sum ) NEW_LINE DEDENT
Find the closest element in Binary Search Tree | Utility that allocates a new node with the given key and NULL left and right pointers . ; Function to find node with minimum absolute difference with given K min_diff -- > minimum difference till now min_diff_key -- > node having minimum absolute difference with K ; If k itself is present ; update min_diff and min_diff_key by checking current node value ; if k is less than ptr -> key then move in left subtree else in right subtree ; Wrapper over maxDiffUtil ( ) ; Initialize minimum difference ; Find value of min_diff_key ( Closest key in tree with k ) ; Driver Code
class newnode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def maxDiffUtil ( ptr , k , min_diff , min_diff_key ) : NEW_LINE INDENT if ptr == None : NEW_LINE INDENT return NEW_LINE DEDENT if ptr . key == k : NEW_LINE INDENT min_diff_key [ 0 ] = k NEW_LINE return NEW_LINE DEDENT if min_diff > abs ( ptr . key - k ) : NEW_LINE INDENT min_diff = abs ( ptr . key - k ) NEW_LINE min_diff_key [ 0 ] = ptr . key NEW_LINE DEDENT if k < ptr . key : NEW_LINE INDENT maxDiffUtil ( ptr . left , k , min_diff , min_diff_key ) NEW_LINE DEDENT else : NEW_LINE INDENT maxDiffUtil ( ptr . right , k , min_diff , min_diff_key ) NEW_LINE DEDENT DEDENT def maxDiff ( root , k ) : NEW_LINE INDENT min_diff , min_diff_key = 999999999999 , [ - 1 ] NEW_LINE maxDiffUtil ( root , k , min_diff , min_diff_key ) NEW_LINE return min_diff_key [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newnode ( 9 ) NEW_LINE root . left = newnode ( 4 ) NEW_LINE root . right = newnode ( 17 ) NEW_LINE root . left . left = newnode ( 3 ) NEW_LINE root . left . right = newnode ( 6 ) NEW_LINE root . left . right . left = newnode ( 5 ) NEW_LINE root . left . right . right = newnode ( 7 ) NEW_LINE root . right . right = newnode ( 22 ) NEW_LINE root . right . right . left = newnode ( 20 ) NEW_LINE k = 18 NEW_LINE print ( maxDiff ( root , k ) ) NEW_LINE DEDENT
Construct a complete binary tree from given array in level order fashion | Helper function that allocates a new node ; Function to insert nodes in level order ; Base case for recursion ; insert left child ; insert right child ; Function to print tree nodes in InOrder fashion ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def insertLevelOrder ( arr , root , i , n ) : NEW_LINE INDENT if i < n : NEW_LINE INDENT temp = newNode ( arr [ i ] ) NEW_LINE root = temp NEW_LINE root . left = insertLevelOrder ( arr , root . left , 2 * i + 1 , n ) NEW_LINE root . right = insertLevelOrder ( arr , root . right , 2 * i + 2 , n ) NEW_LINE DEDENT return root NEW_LINE DEDENT def inOrder ( root ) : NEW_LINE INDENT if root != None : NEW_LINE INDENT inOrder ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE inOrder ( root . right ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 6 , 6 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE root = None NEW_LINE root = insertLevelOrder ( arr , root , 0 , n ) NEW_LINE inOrder ( root ) NEW_LINE DEDENT
Construct Full Binary Tree from given preorder and postorder traversals | A binary tree node has data , pointer to left child and a pointer to right child ; A recursive function to construct Full from pre [ ] and post [ ] . preIndex is used to keep track of index in pre [ ] . l is low index and h is high index for the current subarray in post [ ] ; Base case ; The first node in preorder traversal is root . So take the node at preIndex from preorder and make it root , and increment preIndex ; If the current subarry has only one element , no need to recur ; Search the next element of pre [ ] in post [ ] ; Use the index of element found in postorder to divide postorder array in two parts . Left subtree and right subtree ; The main function to construct Full Binary Tree from given preorder and postorder traversals . This function mainly uses constructTreeUtil ( ) ; A utility function to print inorder traversal of a Binary Tree ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def constructTreeUtil ( pre : list , post : list , l : int , h : int , size : int ) -> Node : NEW_LINE INDENT global preIndex NEW_LINE if ( preIndex >= size or l > h ) : NEW_LINE INDENT return None NEW_LINE DEDENT root = Node ( pre [ preIndex ] ) NEW_LINE preIndex += 1 NEW_LINE if ( l == h or preIndex >= size ) : NEW_LINE INDENT return root NEW_LINE DEDENT i = l NEW_LINE while i <= h : NEW_LINE INDENT if ( pre [ preIndex ] == post [ i ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( i <= h ) : NEW_LINE INDENT root . left = constructTreeUtil ( pre , post , l , i , size ) NEW_LINE root . right = constructTreeUtil ( pre , post , i + 1 , h , size ) NEW_LINE DEDENT return root NEW_LINE DEDENT def constructTree ( pre : list , post : list , size : int ) -> Node : NEW_LINE INDENT global preIndex NEW_LINE return constructTreeUtil ( pre , post , 0 , size - 1 , size ) NEW_LINE DEDENT def printInorder ( node : Node ) -> None : NEW_LINE INDENT if ( node is None ) : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE printInorder ( node . right ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT pre = [ 1 , 2 , 4 , 8 , 9 , 5 , 3 , 6 , 7 ] NEW_LINE post = [ 8 , 9 , 4 , 5 , 2 , 6 , 7 , 3 , 1 ] NEW_LINE size = len ( pre ) NEW_LINE preIndex = 0 NEW_LINE root = constructTree ( pre , post , size ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ " " the ▁ constructed ▁ tree : ▁ " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT
Convert a Binary Tree to Threaded binary tree | Set 2 ( Efficient ) | Converts tree with given root to threaded binary tree . This function returns rightmost child of root . ; Base cases : Tree is empty or has single node ; Find predecessor if it exists ; Find predecessor of root ( Rightmost child in left subtree ) ; Link a thread from predecessor to root . ; If current node is rightmost child ; Recur for right subtree . ; A utility function to find leftmost node in a binary tree rooted with ' root ' . This function is used in inOrder ( ) ; Function to do inorder traversal of a threaded binary tree ; Find the leftmost node in Binary Tree ; If this Node is a thread Node , then go to inorder successor ; Else go to the leftmost child in right subtree ; A utility function to create a new node ; Driver Code ; 1 / \ 2 3 / \ / \ 4 5 6 7
def createThreaded ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . left == None and root . right == None : NEW_LINE INDENT return root NEW_LINE DEDENT if root . left != None : NEW_LINE INDENT l = createThreaded ( root . left ) NEW_LINE l . right = root NEW_LINE l . isThreaded = True NEW_LINE DEDENT if root . right == None : NEW_LINE INDENT return root NEW_LINE DEDENT return createThreaded ( root . right ) NEW_LINE DEDENT def leftMost ( root ) : NEW_LINE INDENT while root != None and root . left != None : NEW_LINE INDENT root = root . left NEW_LINE DEDENT return root NEW_LINE DEDENT def inOrder ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT cur = leftMost ( root ) NEW_LINE while cur != None : NEW_LINE INDENT print ( cur . key , end = " ▁ " ) NEW_LINE if cur . isThreaded : NEW_LINE INDENT cur = cur . right NEW_LINE DEDENT else : NEW_LINE INDENT cur = leftMost ( cur . right ) NEW_LINE DEDENT DEDENT DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = self . right = None NEW_LINE self . key = key NEW_LINE self . isThreaded = None NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE createThreaded ( root ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ created " , " threaded ▁ tree ▁ is " ) NEW_LINE inOrder ( root ) NEW_LINE DEDENT
Inorder Non | A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Function to print inorder traversal using parent pointer ; Start traversal from root ; If left child is not traversed , find the leftmost child ; Print root 's data ; Mark left as done ; If right child exists ; If right child doesn 't exist, move to parent ; If this node is right child of its parent , visit parent 's parent first ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . key = item NEW_LINE self . parent = self . left = self . right = None NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if key < node . key : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE node . left . parent = node NEW_LINE DEDENT elif key > node . key : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE node . right . parent = node NEW_LINE DEDENT return node NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT leftdone = False NEW_LINE while root : NEW_LINE INDENT if leftdone == False : NEW_LINE INDENT while root . left : NEW_LINE INDENT root = root . left NEW_LINE DEDENT DEDENT print ( root . key , end = " ▁ " ) NEW_LINE leftdone = True NEW_LINE if root . right : NEW_LINE INDENT leftdone = False NEW_LINE root = root . right NEW_LINE DEDENT elif root . parent : NEW_LINE INDENT while root . parent and root == root . parent . right : NEW_LINE INDENT root = root . parent NEW_LINE DEDENT if root . parent == None : NEW_LINE INDENT break NEW_LINE DEDENT root = root . parent NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 24 ) NEW_LINE root = insert ( root , 27 ) NEW_LINE root = insert ( root , 29 ) NEW_LINE root = insert ( root , 34 ) NEW_LINE root = insert ( root , 14 ) NEW_LINE root = insert ( root , 4 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE root = insert ( root , 22 ) NEW_LINE root = insert ( root , 13 ) NEW_LINE root = insert ( root , 3 ) NEW_LINE root = insert ( root , 2 ) NEW_LINE root = insert ( root , 6 ) NEW_LINE print ( " Inorder ▁ traversal ▁ is ▁ " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT
Sorted order printing of a given array that represents a BST | Python3 Code for Sorted order printing of a given array that represents a BST ; print left subtree ; print root ; print right subtree ; Driver Code
def printSorted ( arr , start , end ) : NEW_LINE INDENT if start > end : NEW_LINE INDENT return NEW_LINE DEDENT printSorted ( arr , start * 2 + 1 , end ) NEW_LINE print ( arr [ start ] , end = " ▁ " ) NEW_LINE printSorted ( arr , start * 2 + 2 , end ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 5 , 1 , 3 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printSorted ( arr , 0 , arr_size - 1 ) NEW_LINE DEDENT
Floor and Ceil from a BST | A Binary tree node ; Function to find ceil of a given input in BST . If input is more than the max key in BST , return - 1 ; Base Case ; We found equal key ; If root 's key is smaller, ceil must be in right subtree ; Else , either left subtre or root has the ceil value ; Driver program to test above function
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def ceil ( root , inp ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if root . key == inp : NEW_LINE INDENT return root . key NEW_LINE DEDENT if root . key < inp : NEW_LINE INDENT return ceil ( root . right , inp ) NEW_LINE DEDENT val = ceil ( root . left , inp ) NEW_LINE return val if val >= inp else root . key NEW_LINE DEDENT root = Node ( 8 ) NEW_LINE root . left = Node ( 4 ) NEW_LINE root . right = Node ( 12 ) NEW_LINE root . left . left = Node ( 2 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . right . left = Node ( 10 ) NEW_LINE root . right . right = Node ( 14 ) NEW_LINE for i in range ( 16 ) : NEW_LINE INDENT print " % ▁ d ▁ % ▁ d " % ( i , ceil ( root , i ) ) NEW_LINE DEDENT
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree | Utility function to create a new tree node ; A utility function to print inorder traversal of a Binary Tree ; A recursive function to construct Full binary tree from pre [ ] and preM [ ] . preIndex is used to keep track of index in pre [ ] . l is low index and h is high index for the current subarray in preM [ ] ; Base case ; The first node in preorder traversal is root . So take the node at preIndex from preorder and make it root , and increment preIndex ; If the current subarry has only one element , no need to recur ; Search the next element of pre [ ] in preM [ ] ; construct left and right subtrees recursively ; return root ; function to construct full binary tree using its preorder traversal and preorder traversal of its mirror tree ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def prInorder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT prInorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE prInorder ( node . right ) NEW_LINE DEDENT def constructBinaryTreeUtil ( pre , preM , preIndex , l , h , size ) : NEW_LINE INDENT if ( preIndex >= size or l > h ) : NEW_LINE INDENT return None , preIndex NEW_LINE DEDENT root = newNode ( pre [ preIndex ] ) NEW_LINE preIndex += 1 NEW_LINE if ( l == h ) : NEW_LINE INDENT return root , preIndex NEW_LINE DEDENT i = 0 NEW_LINE for i in range ( l , h + 1 ) : NEW_LINE INDENT if ( pre [ preIndex ] == preM [ i ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i <= h ) : NEW_LINE INDENT root . left , preIndex = constructBinaryTreeUtil ( pre , preM , preIndex , i , h , size ) NEW_LINE root . right , preIndex = constructBinaryTreeUtil ( pre , preM , preIndex , l + 1 , i - 1 , size ) NEW_LINE DEDENT return root , preIndex NEW_LINE DEDENT def constructBinaryTree ( root , pre , preMirror , size ) : NEW_LINE INDENT preIndex = 0 NEW_LINE preMIndex = 0 NEW_LINE root , x = constructBinaryTreeUtil ( pre , preMirror , preIndex , 0 , size - 1 , size ) NEW_LINE prInorder ( root ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT preOrder = [ 1 , 2 , 4 , 5 , 3 , 6 , 7 ] NEW_LINE preOrderMirror = [ 1 , 3 , 7 , 6 , 2 , 5 , 4 ] NEW_LINE size = 7 NEW_LINE root = newNode ( 0 ) NEW_LINE constructBinaryTree ( root , preOrder , preOrderMirror , size ) NEW_LINE DEDENT
Floor and Ceil from a BST | A binary tree node has key , . left child and right child ; Helper function to find floor and ceil of a given key in BST ; Display the floor and ceil of a given key in BST . If key is less than the min key in BST , floor will be - 1 ; If key is more than the max key in BST , ceil will be - 1 ; ; Variables ' floor ' and ' ceil ' are passed by reference ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def floorCeilBSTHelper ( root , key ) : NEW_LINE INDENT global floor , ceil NEW_LINE while ( root ) : NEW_LINE INDENT if ( root . data == key ) : NEW_LINE INDENT ceil = root . data NEW_LINE floor = root . data NEW_LINE return NEW_LINE DEDENT if ( key > root . data ) : NEW_LINE INDENT floor = root . data NEW_LINE root = root . right NEW_LINE DEDENT else : NEW_LINE INDENT ceil = root . data NEW_LINE root = root . left NEW_LINE DEDENT DEDENT DEDENT def floorCeilBST ( root , key ) : NEW_LINE INDENT global floor , ceil NEW_LINE floor = - 1 NEW_LINE ceil = - 1 NEW_LINE floorCeilBSTHelper ( root , key ) NEW_LINE print ( key , floor , ceil ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT floor , ceil = - 1 , - 1 NEW_LINE root = Node ( 8 ) NEW_LINE root . left = Node ( 4 ) NEW_LINE root . right = Node ( 12 ) NEW_LINE root . left . left = Node ( 2 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . right . left = Node ( 10 ) NEW_LINE root . right . right = Node ( 14 ) NEW_LINE for i in range ( 16 ) : NEW_LINE INDENT floorCeilBST ( root , i ) NEW_LINE DEDENT DEDENT
How to handle duplicates in Binary Search Tree ? | A utility function to create a new BST node ; A utility function to do inorder traversal of BST ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; If key already exists in BST , increment count and return ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the node with minimum key value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; Given a binary search tree and a key , this function deletes a given key and returns root of modified tree ; base case ; If the key to be deleted is smaller than the root 's key, then it lies in left subtree ; If the key to be deleted is greater than the root 's key, then it lies in right subtree ; if key is same as root 's key ; If key is present more than once , simply decrement count and return ; ElSE , delete the node node with only one child or no child ; node with two children : Get the inorder successor ( smallest in the right subtree ) ; Copy the inorder successor 's content to this node ; Delete the inorder successor ; Driver Code ; Let us create following BST 12 ( 3 ) / \ 10 ( 2 ) 20 ( 1 ) / \ 9 ( 1 ) 11 ( 1 )
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . count = 1 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if root != None : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( root . key , " ( " , root . count , " ) " , end = " ▁ " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT k = newNode ( key ) NEW_LINE return k NEW_LINE DEDENT if key == node . key : NEW_LINE INDENT ( node . count ) += 1 NEW_LINE return node NEW_LINE DEDENT if key < node . key : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT else : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT def minValueNode ( node ) : NEW_LINE INDENT current = node NEW_LINE while current . left != None : NEW_LINE INDENT current = current . left NEW_LINE DEDENT return current NEW_LINE DEDENT def deleteNode ( root , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return root NEW_LINE DEDENT if key < root . key : NEW_LINE INDENT root . left = deleteNode ( root . left , key ) NEW_LINE DEDENT elif key > root . key : NEW_LINE INDENT root . right = deleteNode ( root . right , key ) NEW_LINE DEDENT else : NEW_LINE INDENT if root . count > 1 : NEW_LINE INDENT root . count -= 1 NEW_LINE return root NEW_LINE DEDENT if root . left == None : NEW_LINE INDENT temp = root . right NEW_LINE return temp NEW_LINE DEDENT elif root . right == None : NEW_LINE INDENT temp = root . left NEW_LINE return temp NEW_LINE DEDENT temp = minValueNode ( root . right ) NEW_LINE root . key = temp . key NEW_LINE root . right = deleteNode ( root . right , temp . key ) NEW_LINE DEDENT return root NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 12 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE root = insert ( root , 20 ) NEW_LINE root = insert ( root , 9 ) NEW_LINE root = insert ( root , 11 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE root = insert ( root , 12 ) NEW_LINE root = insert ( root , 12 ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ given ▁ tree " ) NEW_LINE inorder ( root ) NEW_LINE print ( ) NEW_LINE print ( " Delete ▁ 20" ) NEW_LINE root = deleteNode ( root , 20 ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree " ) NEW_LINE inorder ( root ) NEW_LINE print ( ) NEW_LINE print ( " Delete ▁ 12" ) NEW_LINE root = deleteNode ( root , 12 ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree " ) NEW_LINE inorder ( root ) NEW_LINE print ( ) NEW_LINE print ( " Delete ▁ 9" ) NEW_LINE root = deleteNode ( root , 9 ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT
How to implement decrease key or change key in Binary Search Tree ? | A utility function to create a new BST node ; A utility function to do inorder traversal of BST ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the node with minimum key value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; Given a binary search tree and a key , this function deletes the key and returns the new root ; base case ; If the key to be deleted is smaller than the root 's key, then it lies in left subtree ; If the key to be deleted is greater than the root 's key, then it lies in right subtree ; if key is same as root 's key, then this is the node to be deleted ; node with only one child or no child ; node with two children : Get the inorder successor ( smallest in the right subtree ) ; Copy the inorder successor 's content to this node ; Delete the inorder successor ; Function to decrease a key value in Binary Search Tree ; First delete old key value ; Then insert new key value ; Return new root ; Driver Code ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 ; BST is modified to 50 / \ 30 70 / / \ 20 60 80 / 10
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if root != None : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( root . key , end = " ▁ " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if key < node . key : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT else : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT def minValueNode ( node ) : NEW_LINE INDENT current = node NEW_LINE while current . left != None : NEW_LINE INDENT current = current . left NEW_LINE DEDENT return current NEW_LINE DEDENT def deleteNode ( root , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return root NEW_LINE DEDENT if key < root . key : NEW_LINE INDENT root . left = deleteNode ( root . left , key ) NEW_LINE DEDENT elif key > root . key : NEW_LINE INDENT root . right = deleteNode ( root . right , key ) NEW_LINE DEDENT else : NEW_LINE INDENT if root . left == None : NEW_LINE INDENT temp = root . right NEW_LINE return temp NEW_LINE DEDENT elif root . right == None : NEW_LINE INDENT temp = root . left NEW_LINE return temp NEW_LINE DEDENT temp = minValueNode ( root . right ) NEW_LINE root . key = temp . key NEW_LINE root . right = deleteNode ( root . right , temp . key ) NEW_LINE DEDENT return root NEW_LINE DEDENT def changeKey ( root , oldVal , newVal ) : NEW_LINE INDENT root = deleteNode ( root , oldVal ) NEW_LINE root = insert ( root , newVal ) NEW_LINE return root NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 50 ) NEW_LINE root = insert ( root , 30 ) NEW_LINE root = insert ( root , 20 ) NEW_LINE root = insert ( root , 40 ) NEW_LINE root = insert ( root , 70 ) NEW_LINE root = insert ( root , 60 ) NEW_LINE root = insert ( root , 80 ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ given ▁ tree " ) NEW_LINE inorder ( root ) NEW_LINE root = changeKey ( root , 40 , 10 ) NEW_LINE print ( ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT
Print Common Nodes in Two Binary Search Trees | A utility function to create a new node ; Function two print common elements in given two trees ; Create two stacks for two inorder traversals ; append the Nodes of first tree in stack s1 ; append the Nodes of second tree in stack s2 ; Both root1 and root2 are NULL here ; If current keys in two trees are same ; move to the inorder successor ; If Node of first tree is smaller , than that of second tree , then its obvious that the inorder successors of current Node can have same value as that of the second tree Node . Thus , we pop from s2 ; root2 is set to NULL , because we need new Nodes of tree 1 ; Both roots and both stacks are empty ; A utility function to do inorder traversal ; A utility function to insert a new Node with given key in BST ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; return the ( unchanged ) Node pointer ; Driver Code ; Create first tree as shown in example ; Create second tree as shown in example
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def printCommon ( root1 , root2 ) : NEW_LINE INDENT s1 = [ ] NEW_LINE s2 = [ ] NEW_LINE while 1 : NEW_LINE INDENT if root1 : NEW_LINE INDENT s1 . append ( root1 ) NEW_LINE root1 = root1 . left NEW_LINE DEDENT elif root2 : NEW_LINE INDENT s2 . append ( root2 ) NEW_LINE root2 = root2 . left NEW_LINE DEDENT elif len ( s1 ) != 0 and len ( s2 ) != 0 : NEW_LINE INDENT root1 = s1 [ - 1 ] NEW_LINE root2 = s2 [ - 1 ] NEW_LINE if root1 . key == root2 . key : NEW_LINE INDENT print ( root1 . key , end = " ▁ " ) NEW_LINE s1 . pop ( - 1 ) NEW_LINE s2 . pop ( - 1 ) NEW_LINE root1 = root1 . right NEW_LINE root2 = root2 . right NEW_LINE DEDENT elif root1 . key < root2 . key : NEW_LINE INDENT s1 . pop ( - 1 ) NEW_LINE root1 = root1 . right NEW_LINE root2 = None NEW_LINE DEDENT elif root1 . key > root2 . key : NEW_LINE INDENT s2 . pop ( - 1 ) NEW_LINE root2 = root2 . right NEW_LINE root1 = None NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( root . key , end = " ▁ " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if key < node . key : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT elif key > node . key : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = None NEW_LINE root1 = insert ( root1 , 5 ) NEW_LINE root1 = insert ( root1 , 1 ) NEW_LINE root1 = insert ( root1 , 10 ) NEW_LINE root1 = insert ( root1 , 0 ) NEW_LINE root1 = insert ( root1 , 4 ) NEW_LINE root1 = insert ( root1 , 7 ) NEW_LINE root1 = insert ( root1 , 9 ) NEW_LINE root2 = None NEW_LINE root2 = insert ( root2 , 10 ) NEW_LINE root2 = insert ( root2 , 7 ) NEW_LINE root2 = insert ( root2 , 20 ) NEW_LINE root2 = insert ( root2 , 4 ) NEW_LINE root2 = insert ( root2 , 9 ) NEW_LINE print ( " Tree ▁ 1 ▁ : ▁ " ) NEW_LINE inorder ( root1 ) NEW_LINE print ( ) NEW_LINE print ( " Tree ▁ 2 ▁ : ▁ " ) NEW_LINE inorder ( root2 ) NEW_LINE print ( ) NEW_LINE print ( " Common ▁ Nodes : ▁ " ) NEW_LINE printCommon ( root1 , root2 ) NEW_LINE DEDENT
Leaf nodes from Preorder of a Binary Search Tree | Binary Search ; Poto the index in preorder . ; Function to prLeaf Nodes by doing preorder traversal of tree using preorder and inorder arrays . ; If l == r , therefore no right or left subtree . So , it must be leaf Node , print it . ; If array is out of bound , return . ; Finding the index of preorder element in inorder array using binary search . ; Incrementing the index . ; Finding on the left subtree . ; Finding on the right subtree . ; Finds leaf nodes from given preorder traversal . ; To store inorder traversal ; Copy the preorder into another array . ; Finding the inorder by sorting the array . ; Print the Leaf Nodes . ; Driver Code
def binarySearch ( inorder , l , r , d ) : NEW_LINE INDENT mid = ( l + r ) >> 1 NEW_LINE if ( inorder [ mid ] == d ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( inorder [ mid ] > d ) : NEW_LINE INDENT return binarySearch ( inorder , l , mid - 1 , d ) NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( inorder , mid + 1 , r , d ) NEW_LINE DEDENT ind = [ 0 ] NEW_LINE DEDENT def leafNodesRec ( preorder , inorder , l , r , ind , n ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT print ( inorder [ l ] , end = " ▁ " ) NEW_LINE ind [ 0 ] = ind [ 0 ] + 1 NEW_LINE return NEW_LINE DEDENT if ( l < 0 or l > r or r >= n ) : NEW_LINE INDENT return NEW_LINE DEDENT loc = binarySearch ( inorder , l , r , preorder [ ind [ 0 ] ] ) NEW_LINE ind [ 0 ] = ind [ 0 ] + 1 NEW_LINE leafNodesRec ( preorder , inorder , l , loc - 1 , ind , n ) NEW_LINE leafNodesRec ( preorder , inorder , loc + 1 , r , ind , n ) NEW_LINE DEDENT def leafNodes ( preorder , n ) : NEW_LINE INDENT inorder = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT inorder [ i ] = preorder [ i ] NEW_LINE DEDENT inorder . sort ( ) NEW_LINE ind = [ 0 ] NEW_LINE leafNodesRec ( preorder , inorder , 0 , n - 1 , ind , n ) NEW_LINE DEDENT preorder = [ 890 , 325 , 290 , 530 , 965 ] NEW_LINE n = len ( preorder ) NEW_LINE leafNodes ( preorder , n ) NEW_LINE
Leaf nodes from Preorder of a Binary Search Tree | Print the leaf node from the given preorder of BST . ; Since rightmost element is always leaf node . ; Driver code
def leafNode ( preorder , n ) : NEW_LINE INDENT s = [ ] NEW_LINE i = 0 NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT found = False NEW_LINE if preorder [ i ] > preorder [ j ] : NEW_LINE INDENT s . append ( preorder [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT while len ( s ) != 0 : NEW_LINE INDENT if preorder [ j ] > s [ - 1 ] : NEW_LINE INDENT s . pop ( - 1 ) NEW_LINE found = True NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if found : NEW_LINE INDENT print ( preorder [ i ] , end = " ▁ " ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT print ( preorder [ n - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT preorder = [ 890 , 325 , 290 , 530 , 965 ] NEW_LINE n = len ( preorder ) NEW_LINE leafNode ( preorder , n ) NEW_LINE DEDENT
Leaf nodes from Preorder of a Binary Search Tree ( Using Recursion ) | Print the leaf node from the given preorder of BST . ; Driver code
def isLeaf ( pre , i , n , Min , Max ) : NEW_LINE INDENT if i [ 0 ] >= n : NEW_LINE INDENT return False NEW_LINE DEDENT if pre [ i [ 0 ] ] > Min and pre [ i [ 0 ] ] < Max : NEW_LINE INDENT i [ 0 ] += 1 NEW_LINE left = isLeaf ( pre , i , n , Min , pre [ i [ 0 ] - 1 ] ) NEW_LINE right = isLeaf ( pre , i , n , pre [ i [ 0 ] - 1 ] , Max ) NEW_LINE if left == False and right == False : NEW_LINE INDENT print ( pre [ i [ 0 ] - 1 ] , end = " ▁ " ) NEW_LINE DEDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def printLeaves ( preorder , n ) : NEW_LINE INDENT i = [ 0 ] NEW_LINE INT_MIN , INT_MAX = - 999999999999 , 999999999999 NEW_LINE isLeaf ( preorder , i , n , INT_MIN , INT_MAX ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT preorder = [ 890 , 325 , 290 , 530 , 965 ] NEW_LINE n = len ( preorder ) NEW_LINE printLeaves ( preorder , n ) NEW_LINE DEDENT
Binary Search Tree insert with Parent Pointer | A utility function to create a new BST Node ; A utility function to do inorder traversal of BST ; A utility function to insert a new Node with given key in BST ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; Set parent of root of left subtree ; Set parent of root of right subtree ; return the ( unchanged ) Node pointer ; Driver Code ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 ; print iNoder traversal of the BST
class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . key = item NEW_LINE self . left = self . right = None NEW_LINE self . parent = None NEW_LINE DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if root != None : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( " Node ▁ : " , root . key , " , ▁ " , end = " " ) NEW_LINE if root . parent == None : NEW_LINE INDENT print ( " Parent ▁ : ▁ NULL " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Parent ▁ : ▁ " , root . parent . key ) NEW_LINE DEDENT inorder ( root . right ) NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if key < node . key : NEW_LINE INDENT lchild = insert ( node . left , key ) NEW_LINE node . left = lchild NEW_LINE lchild . parent = node NEW_LINE DEDENT elif key > node . key : NEW_LINE INDENT rchild = insert ( node . right , key ) NEW_LINE node . right = rchild NEW_LINE rchild . parent = node NEW_LINE DEDENT return node NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 50 ) NEW_LINE insert ( root , 30 ) NEW_LINE insert ( root , 20 ) NEW_LINE insert ( root , 40 ) NEW_LINE insert ( root , 70 ) NEW_LINE insert ( root , 60 ) NEW_LINE insert ( root , 80 ) NEW_LINE inorder ( root ) NEW_LINE DEDENT
Construct a special tree from given preorder traversal | Utility function to create a new Binary Tree node ; A recursive function to create a Binary Tree from given pre [ ] preLN [ ] arrays . The function returns root of tree . index_ptr is used to update index values in recursive calls . index must be initially passed as 0 ; store the current value ; of index in pre [ ] Base Case : All nodes are constructed ; Allocate memory for this node and increment index for subsequent recursive calls ; If this is an internal node , construct left and right subtrees and link the subtrees ; A wrapper over constructTreeUtil ( ) ; Initialize index as 0. Value of index is used in recursion to maintain the current index in pre [ ] and preLN [ ] arrays . ; This function is used only for testing ; first recur on left child ; then print the data of node ; now recur on right child ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def constructTreeUtil ( pre , preLN , index_ptr , n ) : NEW_LINE INDENT index = index_ptr [ 0 ] NEW_LINE if index == n : NEW_LINE INDENT return None NEW_LINE DEDENT temp = newNode ( pre [ index ] ) NEW_LINE index_ptr [ 0 ] += 1 NEW_LINE if preLN [ index ] == ' N ' : NEW_LINE INDENT temp . left = constructTreeUtil ( pre , preLN , index_ptr , n ) NEW_LINE temp . right = constructTreeUtil ( pre , preLN , index_ptr , n ) NEW_LINE DEDENT return temp NEW_LINE DEDENT def constructTree ( pre , preLN , n ) : NEW_LINE INDENT index = [ 0 ] NEW_LINE return constructTreeUtil ( pre , preLN , index , n ) NEW_LINE DEDENT def printInorder ( node ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE printInorder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE pre = [ 10 , 30 , 20 , 5 , 15 ] NEW_LINE preLN = [ ' N ' , ' N ' , ' L ' , ' L ' , ' L ' ] NEW_LINE n = len ( pre ) NEW_LINE root = constructTree ( pre , preLN , n ) NEW_LINE print ( " Following ▁ is ▁ Inorder ▁ Traversal ▁ of " , " the ▁ Constructed ▁ Binary ▁ Tree : " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT
Minimum Possible value of | ai + aj | function for finding pairs and min value ; initialize smallest and count ; iterate over all pairs ; is abs value is smaller than smallest update smallest and reset count to 1 ; if abs value is equal to smallest increment count value ; print result ; Driver Code
def pairs ( arr , n , k ) : NEW_LINE INDENT smallest = 999999999999 NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if abs ( arr [ i ] + arr [ j ] - k ) < smallest : NEW_LINE INDENT smallest = abs ( arr [ i ] + arr [ j ] - k ) NEW_LINE count = 1 NEW_LINE DEDENT elif abs ( arr [ i ] + arr [ j ] - k ) == smallest : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( " Minimal ▁ Value ▁ = ▁ " , smallest ) NEW_LINE print ( " Total ▁ Pairs ▁ = ▁ " , count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 5 , 7 , 5 , 1 , 9 , 9 ] NEW_LINE k = 12 NEW_LINE n = len ( arr ) NEW_LINE pairs ( arr , n , k ) NEW_LINE DEDENT
Rank of an element in a stream | Python3 program to find rank of an element in a stream . ; Inserting a new Node . ; Updating size of left subtree . ; Function to get Rank of a Node x . ; Step 1. ; Step 2. ; Step 3. ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE self . leftSize = 0 NEW_LINE DEDENT DEDENT def insert ( root , data ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return newNode ( data ) NEW_LINE DEDENT if data <= root . data : NEW_LINE INDENT root . left = insert ( root . left , data ) NEW_LINE root . leftSize += 1 NEW_LINE DEDENT else : NEW_LINE INDENT root . right = insert ( root . right , data ) NEW_LINE DEDENT return root NEW_LINE DEDENT def getRank ( root , x ) : NEW_LINE INDENT if root . data == x : NEW_LINE INDENT return root . leftSize NEW_LINE DEDENT if x < root . data : NEW_LINE INDENT if root . left is None : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return getRank ( root . left , x ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if root . right is None : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT rightSize = getRank ( root . right , x ) NEW_LINE if rightSize == - 1 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return root . leftSize + 1 + rightSize NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 1 , 4 , 4 , 5 , 9 , 7 , 13 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE x = 4 NEW_LINE root = None NEW_LINE for i in range ( n ) : NEW_LINE INDENT root = insert ( root , arr [ i ] ) NEW_LINE DEDENT print ( " Rank ▁ of " , x , " in ▁ stream ▁ is : " , getRank ( root , x ) ) NEW_LINE x = 13 NEW_LINE print ( " Rank ▁ of " , x , " in ▁ stream ▁ is : " , getRank ( root , x ) ) NEW_LINE x = 8 NEW_LINE print ( " Rank ▁ of " , x , " in ▁ stream ▁ is : " , getRank ( root , x ) ) NEW_LINE DEDENT
Rank of an element in a stream | Driver code
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 5 , 1 , 14 , 4 , 15 , 9 , 7 , 20 , 11 ] NEW_LINE key = 20 NEW_LINE arraySize = len ( a ) NEW_LINE count = 0 NEW_LINE for i in range ( arraySize ) : NEW_LINE INDENT if a [ i ] <= key : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( " Rank ▁ of " , key , " in ▁ stream ▁ is : " , count - 1 ) NEW_LINE DEDENT
Special two digit numbers in a Binary Search Tree | A Tree node ; Function to create a new node ; If the tree is empty , return a new node ; If key is smaller than root 's key, go to left subtree and set successor as current node ; return the ( unchanged ) node pointer ; Function to find if number is special or not ; sum_of_digits , prod_of_digits Check if number is two digit or not ; Function to count number of special two digit number ; Driver code ; Function call , to check each node for special two digit number
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( node , data ) : NEW_LINE INDENT global succ NEW_LINE root = node NEW_LINE if ( node == None ) : NEW_LINE INDENT return Node ( data ) NEW_LINE DEDENT if ( data < node . data ) : NEW_LINE INDENT root . left = insert ( node . left , data ) NEW_LINE DEDENT elif ( data > node . data ) : NEW_LINE INDENT root . right = insert ( node . right , data ) NEW_LINE DEDENT return root NEW_LINE DEDENT def check ( num ) : NEW_LINE INDENT sum = 0 NEW_LINE i = num NEW_LINE if ( num < 10 or num > 99 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT sum_of_digits = ( i % 10 ) + ( i // 10 ) NEW_LINE prod_of_digits = ( i % 10 ) * ( i // 10 ) NEW_LINE sum = sum_of_digits + prod_of_digits NEW_LINE DEDENT if ( sum == num ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def countSpecialDigit ( rt ) : NEW_LINE INDENT global c NEW_LINE if ( rt == None ) : NEW_LINE INDENT return NEW_LINE DEDENT else : NEW_LINE INDENT x = check ( rt . data ) NEW_LINE if ( x == 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT countSpecialDigit ( rt . left ) NEW_LINE countSpecialDigit ( rt . right ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE c = 0 NEW_LINE root = insert ( root , 50 ) NEW_LINE root = insert ( root , 29 ) NEW_LINE root = insert ( root , 59 ) NEW_LINE root = insert ( root , 19 ) NEW_LINE root = insert ( root , 53 ) NEW_LINE root = insert ( root , 556 ) NEW_LINE root = insert ( root , 56 ) NEW_LINE root = insert ( root , 94 ) NEW_LINE root = insert ( root , 13 ) NEW_LINE countSpecialDigit ( root ) NEW_LINE print ( c ) NEW_LINE DEDENT
Construct Special Binary Tree from given Inorder traversal | Recursive function to construct binary of size len from Inorder traversal inorder [ ] . Initial values of start and end should be 0 and len - 1. ; Find index of the maximum element from Binary Tree ; Pick the maximum value and make it root ; If this is the only element in inorder [ start . . end ] , then return it ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of the maximum value in arr [ start ... end ] ; Helper class that allocates a new node with the given data and None left and right pointers . ; This funtcion is here just to test buildTree ( ) ; first recur on left child ; then print the data of node ; now recur on right child ; Driver Code ; Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 ; Let us test the built tree by printing Insorder traversal
def buildTree ( inorder , start , end ) : NEW_LINE INDENT if start > end : NEW_LINE INDENT return None NEW_LINE DEDENT i = Max ( inorder , start , end ) NEW_LINE root = newNode ( inorder [ i ] ) NEW_LINE if start == end : NEW_LINE INDENT return root NEW_LINE DEDENT root . left = buildTree ( inorder , start , i - 1 ) NEW_LINE root . right = buildTree ( inorder , i + 1 , end ) NEW_LINE return root NEW_LINE DEDENT def Max ( arr , strt , end ) : NEW_LINE INDENT i , Max = 0 , arr [ strt ] NEW_LINE maxind = strt NEW_LINE for i in range ( strt + 1 , end + 1 ) : NEW_LINE INDENT if arr [ i ] > Max : NEW_LINE INDENT Max = arr [ i ] NEW_LINE maxind = i NEW_LINE DEDENT DEDENT return maxind NEW_LINE DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printInorder ( node ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE printInorder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT inorder = [ 5 , 10 , 40 , 30 , 28 ] NEW_LINE Len = len ( inorder ) NEW_LINE root = buildTree ( inorder , 0 , Len - 1 ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the " , " constructed ▁ tree ▁ is ▁ " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT
Sum of middle row and column in Matrix | Python program to find sum of middle row and column in matrix ; loop for sum of row ; loop for sum of column ; Driver code
def middlesum ( mat , n ) : NEW_LINE INDENT row_sum = 0 NEW_LINE col_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT row_sum += mat [ n // 2 ] [ i ] NEW_LINE DEDENT print ( " Sum ▁ of ▁ middle ▁ row ▁ = ▁ " , row_sum ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT col_sum += mat [ i ] [ n // 2 ] NEW_LINE DEDENT print ( " Sum ▁ of ▁ middle ▁ column ▁ = ▁ " , col_sum ) NEW_LINE DEDENT mat = [ [ 2 , 5 , 7 ] , [ 3 , 7 , 2 ] , [ 5 , 6 , 9 ] ] NEW_LINE middlesum ( mat , 3 ) NEW_LINE
Row | taking MAX 10000 so that time difference can be shown ; accessing element row wise ; accessing element column wise ; Driver code ; Time taken by row major order ; Time taken by column major order
MAX = 1000 NEW_LINE from time import clock NEW_LINE arr = [ [ 0 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def rowMajor ( ) : NEW_LINE INDENT global arr NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT for j in range ( MAX ) : NEW_LINE INDENT arr [ i ] [ j ] += 1 NEW_LINE DEDENT DEDENT DEDENT def colMajor ( ) : NEW_LINE INDENT global arr NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT for j in range ( MAX ) : NEW_LINE INDENT arr [ j ] [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT t = clock ( ) NEW_LINE rowMajor ( ) ; NEW_LINE t = clock ( ) - t NEW_LINE print ( " Row ▁ major ▁ access ▁ time ▁ : { : .2f } ▁ s " . format ( t ) ) NEW_LINE t = clock ( ) NEW_LINE colMajor ( ) NEW_LINE t = clock ( ) - t NEW_LINE print ( " Column ▁ major ▁ access ▁ time ▁ : { : .2f } ▁ s " . format ( t ) ) NEW_LINE DEDENT
Rotate the matrix right by K times | size of matrix ; function to rotate matrix by k times ; temporary array of size M ; within the size of matrix ; copy first M - k elements to temporary array ; copy the elements from k to end to starting ; copy elements from temporary array to end ; function to display the matrix ; Driver code ; rotate matrix by k ; display rotated matrix
M = 3 NEW_LINE N = 3 NEW_LINE matrix = [ [ 12 , 23 , 34 ] , [ 45 , 56 , 67 ] , [ 78 , 89 , 91 ] ] NEW_LINE def rotateMatrix ( k ) : NEW_LINE INDENT global M , N , matrix NEW_LINE temp = [ 0 ] * M NEW_LINE k = k % M NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for t in range ( 0 , M - k ) : NEW_LINE INDENT temp [ t ] = matrix [ i ] [ t ] NEW_LINE DEDENT for j in range ( M - k , M ) : NEW_LINE INDENT matrix [ i ] [ j - M + k ] = matrix [ i ] [ j ] NEW_LINE DEDENT for j in range ( k , M ) : NEW_LINE INDENT matrix [ i ] [ j ] = temp [ j - k ] NEW_LINE DEDENT DEDENT DEDENT def displayMatrix ( ) : NEW_LINE INDENT global M , N , matrix NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , M ) : NEW_LINE INDENT print ( " { } ▁ " . format ( matrix [ i ] [ j ] ) , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT k = 2 NEW_LINE rotateMatrix ( k ) NEW_LINE displayMatrix ( ) NEW_LINE
Program to check Involutory Matrix | Program to implement involutory matrix . ; Function for matrix multiplication . ; Function to check involutory matrix . ; multiply function call . ; Driver Code ; Function call . If function return true then if part will execute otherwise else part will execute .
N = 3 ; NEW_LINE def multiply ( mat , res ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT res [ i ] [ j ] = 0 ; NEW_LINE for k in range ( N ) : NEW_LINE INDENT res [ i ] [ j ] += mat [ i ] [ k ] * mat [ k ] [ j ] ; NEW_LINE DEDENT DEDENT DEDENT return res ; NEW_LINE DEDENT def InvolutoryMatrix ( mat ) : NEW_LINE INDENT res = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] ; NEW_LINE res = multiply ( mat , res ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( i == j and res [ i ] [ j ] != 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( i != j and res [ i ] [ j ] != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT DEDENT return True ; NEW_LINE DEDENT mat = [ [ 1 , 0 , 0 ] , [ 0 , - 1 , 0 ] , [ 0 , 0 , - 1 ] ] ; NEW_LINE if ( InvolutoryMatrix ( mat ) ) : NEW_LINE INDENT print ( " Involutory ▁ Matrix " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Involutory ▁ Matrix " ) ; NEW_LINE DEDENT