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 ad... |
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 ;... | 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 ... |
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 ... | 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 . ap... |
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... | 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 (... |
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 W... | 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 N... |
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 t... | 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... |
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 n... | 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 ... |
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 n... | 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 = he... |
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... | 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... |
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 ; Drive... | 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 IND... |
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... |
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 ;... | 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... |
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 distan... | 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 I... |
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... | 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 ... |
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. Cha... | 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 ) : NE... |
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 p... |
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 l... | 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 , da... |
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 ( se... | 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 = secon... |
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 i... | 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_LIN... |
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 s... | 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 .... |
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 las... | 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_... |
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 i... | 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 == ... |
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 n... | 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_... |
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... | 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 . d... |
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 le... | 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 . r... |
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 findin... | 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 ) ) : ... |
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 th... | 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 DE... |
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 ) NE... |
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 ; functio... | 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 ... |
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 . ; Firs... | 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 ... |
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 ... |
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 ... | 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 ... |
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 ' ... | 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 r... |
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 ... | 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 rig... |
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 pr... | 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... |
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 )... | 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 ... |
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 - pr... | 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 ) : NE... |
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 , onl... | 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 ) : NE... |
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 Inor... | 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 DEDEN... |
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 ) . ... | 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 d... |
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... | 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 ... |
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 inor... | 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... |
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 ... | 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 ... |
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 β tha... | 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 ... |
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 ) ... |
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 ; E... | 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... |
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 no... | 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 (... |
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 funct... | 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_LI... |
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 T... |
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 ( s... |
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... | 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 ... |
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 n... | 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... |
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 I... |
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 N... |
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 conta... | 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 DED... |
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 conta... | 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 DED... |
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 ... | 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 : NE... |
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 th... | 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 cu... |
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... | 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 = getCount... |
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 .... | 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 :... |
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 ... | 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... |
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 i... | 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 cre... |
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 em... | 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 ... |
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 ... | 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 , ... |
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 grea... | 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 [ ... |
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_... |
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 diff... | 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 : NE... |
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... | 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 ==... |
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 . l... |
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 ... | 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 ( preIn... |
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 ) ; L... | 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 . isT... |
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... | 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 : NE... |
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 ar... |
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 te... | 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 retu... |
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 ... | 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... |
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... | 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_L... |
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 ; Othe... | 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 ( roo... |
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 ... | 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 (... |
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 ;... | 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 ( root... |
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... | 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 ( ... |
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 [... |
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... |
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 subtre... | 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 β : " ... |
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... | 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 retur... |
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... |
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 ... |
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 , ... |
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 ;... | 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_L... |
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 on... | 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 ) NE... |
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 DEDE... |
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 colMa... |
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 ; D... | 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 [... |
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 DED... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.