code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
# Python code to convert a sorted array # to a balanced Binary Search Tree # binary tree node class Node: def __init__(self, d): self.data = d self.left = None self.right = None # function to convert sorted array to a # balanced BST # input : sorted array of integers # output: root node of balanced BST def sortedArrayToBST(arr): if not arr: return None # find middle index mid = (len(arr)) // 2 # make the middle element the root root = Node(arr[mid]) # left subtree of root has all # values <arr[mid] root.left = sortedArrayToBST(arr[:mid]) # right subtree of root has all # values >arr[mid] root.right = sortedArrayToBST(arr[mid+1:]) return root # A utility function to print the preorder # traversal of the BST def preOrder(node): if not node: return print node.data, preOrder(node.left) preOrder(node.right) # driver program to test above function """ Constructed balanced BST is 4 / \ 2 6 / \ / \ 1 3 5 7 """ arr = [1, 2, 3, 4, 5, 6, 7] root = sortedArrayToBST(arr) print "PreOrder Traversal of constructed BST ", preOrder(root) # This code is contributed by Ishita Tripathi
logn
linear
# Python3 program to transform a BST to sum tree class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Recursive function to transform a BST to sum tree. # This function traverses the tree in reverse inorder so # that we have visited all greater key nodes of the currently # visited node def transformTreeUtil(root): # Base case if (root == None): return # Recur for right subtree transformTreeUtil(root.right) # Update sum global sum sum = sum + root.data # Store old sum in current node root.data = sum - root.data # Recur for left subtree transformTreeUtil(root.left) # A wrapper over transformTreeUtil() def transformTree(root): # sum = 0 #Initialize sum transformTreeUtil(root) # A utility function to prindorder traversal of a # binary tree def printInorder(root): if (root == None): return printInorder(root.left) print(root.data, end = " ") printInorder(root.right) # Driver Program to test above functions if __name__ == '__main__': sum=0 root = Node(11) root.left = Node(2) root.right = Node(29) root.left.left = Node(1) root.left.right = Node(7) root.right.left = Node(15) root.right.right = Node(40) root.right.right.left = Node(35) print("Inorder Traversal of given tree") printInorder(root) transformTree(root) print("\nInorder Traversal of transformed tree") printInorder(root) # This code is contributed by mohit kumar 29
linear
linear
# Python3 program to construct all unique # BSTs for keys from 1 to n # Binary Tree Node """ A utility function to create a new BST node """ class newNode: # Construct to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None # Utility function to print Min-heap # level by level def printLevelOrder(root): # Base Case if (root == None): return # Create an empty queue for level # order traversal q = [] q.append(root) while (len(q)): nodeCount = len(q) while (nodeCount > 0) : node = q[0] print(node.data, end = " " ) q.pop(0) if (node.left) : q.append(node.left) if (node.right) : q.append(node.right) nodeCount -= 1 print() # A simple recursive function to convert a # given Binary Search tree to Sorted Linked # List root -. Root of Binary Search Tree def BSTToSortedLL(root, head_ref): # Base cases if(root == None) : return # Recursively convert right subtree BSTToSortedLL(root.right, head_ref) # insert root into linked list root.right = head_ref[0] # Change left pointer of previous # head to point to None if (head_ref[0] != None): (head_ref[0]).left = None # Change head of linked list head_ref[0] = root # Recursively convert left subtree BSTToSortedLL(root.left, head_ref) # Function to convert a sorted Linked # List to Min-Heap. # root -. root[0] of Min-Heap # head -. Pointer to head node of # sorted linked list def SortedLLToMinHeap( root, head) : # Base Case if (head == None) : return # queue to store the parent nodes q = [] # The first node is always the # root node root[0] = head[0] # advance the pointer to the next node head[0] = head[0].right # set right child to None root[0].right = None # add first node to the queue q.append(root[0]) # run until the end of linked list # is reached while (head[0] != None) : # Take the parent node from the q # and remove it from q parent = q[0] q.pop(0) # Take next two nodes from the linked # list and Add them as children of the # current parent node. Also in push them # into the queue so that they will be # parents to the future nodes leftChild = head[0] head[0] = head[0].right # advance linked list to next node leftChild.right = None # set its right child to None q.append(leftChild) # Assign the left child of parent parent.left = leftChild if (head) : rightChild = head[0] head[0] = head[0].right # advance linked list to next node rightChild.right = None # set its right child to None q.append(rightChild) # Assign the right child of parent parent.right = rightChild # Function to convert BST into a Min-Heap # without using any extra space def BSTToMinHeap(root): # head of Linked List head = [None] # Convert a given BST to Sorted Linked List BSTToSortedLL(root, head) # set root as None root = [None] # Convert Sorted Linked List to Min-Heap SortedLLToMinHeap(root, head) return root # Driver Code if __name__ == '__main__': """ Constructing below tree 8 / \ 4 12 / \ / \ 2 6 10 14 """ root = newNode(8) root.left = newNode(4) root.right = newNode(12) root.right.left = newNode(10) root.right.right = newNode(14) root.left.left = newNode(2) root.left.right = newNode(6) root = BSTToMinHeap(root) """ Output - Min Heap 2 / \ 4 6 / \ / \ 8 10 12 14 """ printLevelOrder(*root) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10)
linear
linear
# Python3 implementation to convert the # given BST to Min Heap # structure of a node of BST class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # function for the inorder traversal # of the tree so as to store the node # values in 'arr' in sorted order def inorderTraversal(root, arr): if root == None: return # first recur on left subtree inorderTraversal(root.left, arr) # then copy the data of the node arr.append(root.data) # now recur for right subtree inorderTraversal(root.right, arr) # function to convert the given # BST to MIN HEAP performs preorder # traversal of the tree def BSTToMinHeap(root, arr, i): if root == None: return # first copy data at index 'i' of # 'arr' to the node i[0] += 1 root.data = arr[i[0]] # then recur on left subtree BSTToMinHeap(root.left, arr, i) # now recur on right subtree BSTToMinHeap(root.right, arr, i) # utility function to convert the # given BST to MIN HEAP def convertToMinHeapUtil(root): # vector to store the data of # all the nodes of the BST arr = [] i = [-1] # inorder traversal to populate 'arr' inorderTraversal(root, arr) # BST to MIN HEAP conversion BSTToMinHeap(root, arr, i) # function for the preorder traversal # of the tree def preorderTraversal(root): if root == None: return # first print the root's data print(root.data, end=" ") # then recur on left subtree preorderTraversal(root.left) # now recur on right subtree preorderTraversal(root.right) # Driver's Code if __name__ == '__main__': # BST formation root = Node(4) root.left = Node(2) root.right = Node(6) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(5) root.right.right = Node(7) # Function call convertToMinHeapUtil(root) print("Preorder Traversal:") preorderTraversal(root) # This code is contributed # by PranchalK
linear
linear
# Python3 program to convert a Binary tree # to BST using sets as containers. # Binary Tree Node """ A utility function to create a new BST node """ class newNode: # Construct to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None # function to store the nodes in set # while doing inorder traversal. def storeinorderInSet(root, s): if (not root) : return # visit the left subtree first storeinorderInSet(root.left, s) # insertion takes order of O(logn) # for sets s.add(root.data) # visit the right subtree storeinorderInSet(root.right, s) # Time complexity = O(nlogn) # function to copy items of set one by one # to the tree while doing inorder traversal def setToBST(s, root) : # base condition if (not root): return # first move to the left subtree and # update items setToBST(s, root.left) # iterator initially pointing to # the beginning of set it = next(iter(s)) # copying the item at beginning of # set(sorted) to the tree. root.data = it # now erasing the beginning item from set. s.remove(it) # now move to right subtree # and update items setToBST(s, root.right) # T(n) = O(nlogn) time # Converts Binary tree to BST. def binaryTreeToBST(root): s = set() # populating the set with the tree's # inorder traversal data storeinorderInSet(root, s) # now sets are by default sorted as # they are implemented using self- # balancing BST # copying items from set to the tree # while inorder traversal which makes a BST setToBST(s, root) # Time complexity = O(nlogn), # Auxiliary Space = O(n) for set. # function to do inorder traversal def inorder(root) : if (not root) : return inorder(root.left) print(root.data, end = " ") inorder(root.right) # Driver Code if __name__ == '__main__': root = newNode(5) root.left = newNode(7) root.right = newNode(9) root.right.left = newNode(10) root.left.left = newNode(1) root.left.right = newNode(6) root.right.right = newNode(11) """ Constructing tree given in the above figure 5 / \ 7 9 /\ / \ 1 6 10 11 """ # converting the above Binary tree to BST binaryTreeToBST(root) print("Inorder traversal of BST is: ") inorder(root) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10)
linear
nlogn
# Class to create a new Tree Node class newNode: def __init__(self, data: int): self.data = data self.left = None self.right = None def inorder(root: newNode): if root: inorder(root.left) print(root.data, end=" ") inorder(root.right) def merge(root1: newNode, root2: newNode): # s1 is stack to hold nodes of first BST s1 = [] # Current node of first BST current1 = root1 # s2 is stack to hold nodes of first BST s2 = [] # Current node of second BST current2 = root2 # If first BST is empty then the output is the # inorder traversal of the second BST if not root1: return inorder(root2) # If the second BST is empty then the output is the # inorder traversal of the first BST if not root2: return inorder(root1) # Run the loop while there are nodes not yet printed. # The nodes may be in stack(explored, but not printed) # or may be not yet explored while current1 or s1 or current2 or s2: # Following steps follow iterative Inorder Traversal if current1 or current2: # Reach the leftmost node of both BSTs and push ancestors of # leftmost nodes to stack s1 and s2 respectively if current1: s1.append(current1) current1 = current1.left if current2: s2.append(current2) current2 = current2.left else: # If we reach a NULL node and either of the stacks is empty, # then one tree is exhausted, print the other tree if not s1: while s2: current2 = s2.pop() current2.left = None inorder(current2) return if not s2: while s1: current1 = s1.pop() current1.left = None inorder(current1) return # Pop an element from both stacks and compare the # popped elements current1 = s1.pop() current2 = s2.pop() # If element of first tree is smaller, then print it # and push the right subtree. If the element is larger, # then we push it back to the corresponding stack. if current1.data < current2.data: print(current1.data, end=" ") current1 = current1.right s2.append(current2) current2 = None else: print(current2.data, end=" ") current2 = current2.right s1.append(current1) current1 = None # Driver code def main(): # Let us create the following tree as first tree # 3 # / \ # 1 5 root1 = newNode(3) root1.left = newNode(1) root1.right = newNode(5) # Let us create the following tree as second tree # 4 # / \ # 2 6 # root2 = newNode(4) root2.left = newNode(2) root2.right = newNode(6) merge(root1, root2) if __name__ == "__main__": main() # This code is contributed by Koushik Reddy Bukkasamudram
logn
linear
# Python program to Merge two BSTs with limited extra space # Structure of a BST Node class Node: def __init__(self, val): self.val = val self.left = None self.right = None def mergeTwoBST(root1, root2): res = [] s1, s2 = [], [] while root1 or root2 or s1 or s2: while root1: s1.append(root1) root1 = root1.left while root2: s2.append(root2) root2 = root2.left # Step 3 Case 1:- if not s2 or (s1 and s1[-1].val <= s2[-1].val): root1 = s1[-1] del s1[-1] res.append(root1.val) root1 = root1.right # Step 3 case 2 :- else: root2 = s2[-1] del s2[-1] res.append(root2.val) root2 = root2.right return res # Driver program to test above functions if __name__ == '__main__': root1 = None root2 = None ''' Let us create the following tree as first tree 3 / \ 1 5 ''' root1 = Node(3) root1.left = Node(1) root1.right = Node(5) ''' Let us create the following tree as second tree 4 / \ 2 6 ''' root2 = Node(4) root2.left = Node(2) root2.right = Node(6) ans = mergeTwoBST(root1, root2) for x in ans: print (x, end=" ") # This code is contributed by Tapesh(tapeshdua420)
logn
linear
# Python3 program to find the node with minimum value in bst # A binary tree node class Node: # Constructor to create a new node def __init__(self, key): self.data = key self.left = None self.right = None """ 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). """ def insert(node, data): # 1. If the tree is empty, return a new, # single node if node is None: return (Node(data)) else: # 2. Otherwise, recur down the tree if data <= node.data: node.left = insert(node.left, data) else: node.right = insert(node.right, data) # Return the (unchanged) node pointer return node """ 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. """ def minValue(node): current = node # loop down to find the leftmost leaf while(current.left is not None): current = current.left return current.data # Driver code if __name__ == '__main__': root = None root = insert(root, 4) insert(root, 2) insert(root, 1) insert(root, 3) insert(root, 6) insert(root, 5) # Function call print("\nMinimum value in BST is %d" % (minValue(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
linear
# Python program for an efficient solution to check if # a given array can represent Preorder traversal of # a Binary Search Tree INT_MIN = -2**32 def canRepresentBST(pre): # Create an empty stack s = [] # Initialize current root as minimum possible value root = INT_MIN # Traverse given array for value in pre: #NOTE:value is equal to pre[i] according to the #given algo # If we find a node who is on the right side # and smaller than root, return False if value < root : return False # If value(pre[i]) is in right subtree of stack top, # Keep removing items smaller than value # and make the last removed items as new root while(len(s) > 0 and s[-1] < value) : root = s.pop() # At this point either stack is empty or value # is smaller than root, push value s.append(value) return True # Driver Program pre1 = [40 , 30 , 35 , 80 , 100] print ("true" if canRepresentBST(pre1) == True else "false") pre2 = [40 , 30 , 35 , 20 , 80 , 100] print ("true" if canRepresentBST(pre2) == True else "false") # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
linear
# Python3 program to illustrate if a given array can represent # a preorder traversal of a BST or not import sys preIndex = 0 # We are actually not building the tree def buildBST_helper(n, pre, Min, Max): global preIndex if (preIndex >= n): return if (Min <= pre[preIndex] and pre[preIndex] <= Max): # build node rootData = pre[preIndex] preIndex+=1 # build left subtree buildBST_helper(n, pre, Min, rootData) # build right subtree buildBST_helper(n, pre, rootData, Max) # else # return NULL def canRepresentBST(arr, N): global preIndex # code here Min, Max = sys.maxsize, -sys.maxsize buildBST_helper(N, arr, Min, Max) if preIndex == N: return True return False preorder1 = [ 2, 4, 3 ] """ 2 \ 4 / 3 """ n1 = len(preorder1) if (not canRepresentBST(preorder1, n1)): print("preorder1 can represent BST"); else: print("preorder1 can not represent BST :(") preorder2 = [ 5, 3, 4, 1, 6, 10 ] n2 = len(preorder2) """ 5 / \ 3 1 \ / \ 4 6 10 """ if (canRepresentBST(preorder2, n2)): print("preorder2 can represent BST") else: print("preorder2 can not represent BST :(") preorder3 = [ 5, 3, 4, 8, 6, 10 ] n3 = len(preorder3) """ 5 / \ 3 8 \ / \ 4 6 10 """ if (not canRepresentBST(preorder3, n3)): print("preorder3 can represent BST") else: print("preorder3 can not represent BST :(")
logn
linear
# A recursive python program to find LCA of two nodes # n1 and n2 # A Binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to find LCA of n1 and n2. The function assumes # that both n1 and n2 are present in BST def lca(root, n1, n2): # Base Case if root is None: return None # If both n1 and n2 are smaller than root, then LCA # lies in left if(root.data > n1 and root.data > n2): return lca(root.left, n1, n2) # If both n1 and n2 are greater than root, then LCA # lies in right if(root.data < n1 and root.data < n2): return lca(root.right, n1, n2) return root # Driver program to test above function # Driver code root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(4) root.left.right = Node(12) root.left.right.left = Node(10) root.left.right.right = Node(14) # Function calls n1 = 10 n2 = 14 t = lca(root, n1, n2) print("LCA of %d and %d is %d" % (n1, n2, t.data)) n1 = 14 n2 = 8 t = lca(root, n1, n2) print("LCA of %d and %d is %d" % (n1, n2, t.data)) n1 = 10 n2 = 22 t = lca(root, n1, n2) print("LCA of %d and %d is %d" % (n1, n2, t.data)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
logn
constant
# A recursive python program to find LCA of two nodes # n1 and n2 # A Binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to find LCA of n1 and n2. # The function assumes that both # n1 and n2 are present in BST def lca(root, n1, n2): while root: # If both n1 and n2 are smaller than root, # then LCA lies in left if root.data > n1 and root.data > n2: root = root.left # If both n1 and n2 are greater than root, # then LCA lies in right elif root.data < n1 and root.data < n2: root = root.right else: break return root # Driver code if __name__ == '__main__': root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(4) root.left.right = Node(12) root.left.right.left = Node(10) root.left.right.right = Node(14) # Function calls n1 = 10 n2 = 14 t = lca(root, n1, n2) print("LCA of %d and %d is %d" % (n1, n2, t.data)) n1 = 14 n2 = 8 t = lca(root, n1, n2) print("LCA of %d and %d is %d" % (n1, n2, t.data)) n1 = 10 n2 = 22 t = lca(root, n1, n2) print("LCA of %d and %d is %d" % (n1, n2, t.data)) # This Code is Contributed by Sumit Bhardwaj (Timus)
constant
constant
# A Python3 program to check for Identical # BSTs without building the trees # # The main function that checks if two # arrays a[] and b[] of size n construct # same BST. The two values 'min' and 'max' # decide whether the call is made for left # subtree or right subtree of a parent # element. The indexes i1 and i2 are the # indexes in (a[] and b[]) after which we # search the left or right child. Initially, # the call is made for INT_MIN and INT_MAX # as 'min' and 'max' respectively, because # root has no parent. i1 and i2 are just # after the indexes of the parent element in a[] and b[]. */ def isSameBSTUtil(a, b, n, i1, i2, min, max): # # Search for a value satisfying the # constraints of min and max in a[] and # b[]. If the parent element is a leaf # node then there must be some elements # in a[] and b[] satisfying constraint. */ j, k = i1, i2 while j < n: if (a[j] > min and a[j] < max): break; j += 1 while k<n: if (b[k] > min and b[k] < max): break k += 1 # If the parent element is leaf in both arrays */ if (j == n and k == n): return True # Return false if any of the following is true # a) If the parent element is leaf in one array, # but non-leaf in other. # b) The elements satisfying constraints are # not same. We either search for left # child or right child of the parent # element (decided by min and max values). # The child found must be same in both arrays */ if (((j == n) ^ (k == n)) or a[j] != b[k]): return False # Make the current child as parent and # recursively check for left and right # subtrees of it. Note that we can also # pass a[k] in place of a[j] as they # are both are same */ return isSameBSTUtil(a, b, n, j + 1, k + 1, a[j], max) and isSameBSTUtil(a, b, n, j + 1, k + 1, min, a[j]) #Left Subtree # A wrapper over isSameBSTUtil() def isSameBST(a, b, n): return isSameBSTUtil(a, b, n, 0, 0, -10**9, 10**9) # Driver code if __name__ == '__main__': a = [8, 3, 6, 1, 4, 7, 10, 14, 13] b = [8, 10, 14, 3, 6, 4, 1, 7, 13] n = len(a) if(isSameBST(a, b, n)): print("BSTs are same") else: print("BSTs not same") # This code is contributed by mohit kumar 29.
linear
quadratic
# Python3 program to find k'th largest # element in BST class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A function to find k'th largest # element in a given tree. def kthLargestUtil(root, k, c): # Base cases, the second condition # is important to avoid unnecessary # recursive calls if root == None or c[0] >= k: return # Follow reverse inorder traversal # so that the largest element is # visited first kthLargestUtil(root.right, k, c) # Increment count of visited nodes c[0] += 1 # If c becomes k now, then this is # the k'th largest if c[0] == k: print("K'th largest element is", root.key) return # Recur for left subtree kthLargestUtil(root.left, k, c) # Function to find k'th largest element def kthLargest(root, k): # Initialize count of nodes # visited as 0 c = [0] # Note that c is passed by reference kthLargestUtil(root, k, c) # A utility function to insert a new # node with given key in BST */ def insert(node, key): # If the tree is empty, # return a new node if node == None: return Node(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Driver Code if __name__ == '__main__': # Let us create following BST # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 */ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) for k in range(1,8): kthLargest(root, k) # This code is contributed by PranchalK
logn
linear
# Python3 code for finding K-th largest # Node using O(1) extra memory and # reverse Morris traversal. # helper function to create a new Node class newNode: def __init__(self, data): self.data = data self.right = self.left = None def KthLargestUsingMorrisTraversal(root, k): curr = root Klargest = None # count variable to keep count # of visited Nodes count = 0 while (curr != None): # if right child is None if (curr.right == None): # first increment count and # check if count = k count += 1 if (count == k): Klargest = curr # otherwise move to the left child curr = curr.left else: # find inorder successor of # current Node succ = curr.right while (succ.left != None and succ.left != curr): succ = succ.left if (succ.left == None): # set left child of successor # to the current Node succ.left = curr # move current to its right curr = curr.right # restoring the tree back to # original binary search tree # removing threaded links else: succ.left = None count += 1 if (count == k): Klargest = curr # move current to its left child curr = curr.left return Klargest # Driver Code if __name__ == '__main__': # Constructed binary tree is # 4 # / \ # 2 7 # / \ / \ # 1 3 6 10 root = newNode(4) root.left = newNode(2) root.right = newNode(7) root.left.left = newNode(1) root.left.right = newNode(3) root.right.left = newNode(6) root.right.right = newNode(10) print("Finding K-th largest Node in BST : ", KthLargestUsingMorrisTraversal(root, 2).data) # This code is contributed by PranchalK
constant
linear
# Python 3 program to find k'th # largest element in BST # A BST node class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A function to find def KSmallestUsingMorris(root, k): # Count to iterate over elements # till we get the kth smallest number count = 0 ksmall = -9999999999 # store the Kth smallest curr = root # to store the current node while curr != None: # 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 curr.left == None: count += 1 # if count is equal to K then we # found the kth smallest, so store # it in ksmall if count == k: ksmall = curr.key # go to current's right child curr = curr.right else: # we create links to Inorder Successor # and count using these links pre = curr.left while (pre.right != None and pre.right != curr): pre = pre.right # building links if pre.right == None: # link made to Inorder Successor pre.right = curr curr = curr.left # While breaking the links in so made # temporary threaded tree we will check # for the K smallest condition else: # Revert the changes made in if part # (break link from the Inorder Successor) pre.right = None count += 1 # If count is equal to K then we # found the kth smallest and so # store it in ksmall if count == k: ksmall = curr.key curr = curr.right return ksmall # return the found value # A utility function to insert a new # node with given key in BST def insert(node, key): # If the tree is empty, # return a new node if node == None: return Node(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Driver Code if __name__ == '__main__': # Let us create following BST # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) for k in range(1,8): print(KSmallestUsingMorris(root, k), end = " ") # This code is contributed by PranchalK
constant
linear
# Python 3 program to check if a given array # is sorted or not. # Function that returns true if array is Inorder # traversal of any Binary Search Tree or not. def isInorder(arr, n): # Array has one or no element if (n == 0 or n == 1): return True for i in range(1, n, 1): # Unsorted pair found if (arr[i - 1] > arr[i]): return False # No unsorted pair found return True # Driver code if __name__ == '__main__': arr = [19, 23, 25, 30, 45] n = len(arr) if (isInorder(arr, n)): print("Yes") else: print("No") # This code is contributed by # Sahil_Shelangia
constant
linear
# Python3 program to check if two BSTs contains # same set of elements # BST Node class Node: def __init__(self): self.val = 0 self.left = None self.right = None # Utility function to create Node def Node_(val1): temp = Node() temp.val = val1 temp.left = temp.right = None return temp s = {} # function to insert elements of the # tree to map m def insertToHash(root): if (root == None): return insertToHash(root.left) s.add(root.data) insertToHash(root.right) # function to check if the two BSTs contain # same set of elements def checkBSTs(root1, root2): # Base cases if (root1 != None and root2 != None) : return True if ((root1 == None and root2 != None) or (root1 != None and root2 == None)): return False # Create two hash sets and store # elements both BSTs in them. s1 = {} s2 = {} s = s1 insertToHash(root1) s1 = s s = s2 insertToHash(root2) s2 = s # Return True if both hash sets # contain same elements. return (s1 == (s2)) # Driver code # First BST root1 = Node_(15) root1.left = Node_(10) root1.right = Node_(20) root1.left.left = Node_(5) root1.left.right = Node_(12) root1.right.right = Node_(25) # Second BST root2 = Node_(15) root2.left = Node_(12) root2.right = Node_(20) root2.left.left = Node_(5) root2.left.left.right = Node_(10) root2.right.right = Node_(25) # check if two BSTs have same set of elements if (checkBSTs(root1, root2)): print("YES") else: print("NO") # This code is contributed by Arnab Kundu
linear
linear
# Python3 program to check if two BSTs contains # same set of elements # BST Node class Node: def __init__(self): self.data = 0 self.left = None self.right = None # Utility function to create Node def Node_(val1): temp = Node() temp.data = val1 temp.left = temp.right = None return temp v = [] # function to insert elements of the # tree to map m def storeInorder(root): if (root == None): return storeInorder(root.left) v.append(root.data) storeInorder(root.right) # function to check if the two BSTs contain # same set of elements def checkBSTs(root1, root2): # Base cases if (root1 == None and root2 == None) : return True if ((root1 == None and root2 != None) or \ (root1 != None and root2 == None)): return False # Create two hash sets and store # elements both BSTs in them. v1 = [] v2 = [] v = v1 storeInorder(root1) v1 = v v = v2 storeInorder(root2) v2 = v # Return True if both hash sets # contain same elements. return (v1 == v2) # Driver code # First BST root1 = Node_(15) root1.left = Node_(10) root1.right = Node_(20) root1.left.left = Node_(5) root1.left.right = Node_(12) root1.right.right = Node_(25) # Second BST root2 = Node_(15) root2.left = Node_(12) root2.right = Node_(20) root2.left.left = Node_(5) root2.left.left.right = Node_(10) root2.right.right = Node_(25) # check if two BSTs have same set of elements if (checkBSTs(root1, root2)): print("YES") else: print("NO") # This code is contributed by SHUBHAMSINGH10
linear
linear
# Python3 implementation to count pairs # from two BSTs whose sum is equal to a # given value x # Structure of a node of BST class getNode: def __init__(self, data): self.data = data self.left = None self.right = None # Function to count pairs from two BSTs # whose sum is equal to a given value x def countPairs(root1, root2, x): # If either of the tree is empty if (root1 == None or root2 == None): return 0 # Stack 'st1' used for the inorder # traversal of BST 1 # stack 'st2' used for the reverse # inorder traversal of BST 2 st1 = [] st2 = [] count = 3 # The loop will break when either # of two traversals gets completed while (1): # To find next node in inorder # traversal of BST 1 while (root1 != None): st1.append(root1) root1 = root1.left # To find next node in reverse # inorder traversal of BST 2 while (root2 != None): st2.append(root2) root2 = root2.right # If either gets empty then corresponding # tree traversal is completed if (len(st1) or len(st2)): break top1 = st1[len(st1) - 1] top2 = st2[len(st2) - 1] # If the sum of the node's is equal to 'x' if ((top1.data + top2.data) == x): # Increment count count += 1 # Pop nodes from the respective stacks st1.remove(st1[len(st1) - 1]) st2.remove(st2[len(st2) - 1]) # Insert next possible node in the # respective stacks root1 = top1.right root2 = top2.left # Move to next possible node in the # inorder traversal of BST 1 elif ((top1.data + top2.data) < x): st1.remove(st1[len(st1) - 1]) root1 = top1.right # Move to next possible node in the # reverse inorder traversal of BST 2 else: st2.remove(st2[len(st2) - 1]) root2 = top2.left # Required count of pairs return count # Driver code if __name__ == '__main__': # Formation of BST 1 ''' 5 / \ 3 7 / \ / \ 2 4 6 8 ''' root1 = getNode(5) root1.left = getNode(3) root1.right = getNode(7) root1.left.left = getNode(2) root1.left.right = getNode(4) root1.right.left = getNode(6) root1.right.right = getNode(8) # Formation of BST 2 ''' 10 / \ 6 15 / \ / \ 3 8 11 18 ''' root2 = getNode(10) root2.left = getNode(6) root2.right = getNode(15) root2.left.left = getNode(3) root2.left.right = getNode(8) root2.right.left = getNode(11) root2.right.right = getNode(18) x = 16 print("Pairs = ", countPairs(root1, root2, x)) # This code is contributed by bgangwar59
logn
linear
# Python program to find closest # value in Binary search Tree _MIN=-2147483648 _MAX=2147483648 # Helper function that allocates # a new node with the given data # and None left and right pointers. class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None """ A utility function to insert a new node with given key in BST """ def insert(node,key): """ If the tree is empty, return a new node """ if (node == None): return newNode(key) """ Otherwise, recur down the tree """ if (key < node.data): node.left = insert(node.left, key) elif (key > node.data): node.right = insert(node.right, key) """ return the (unchanged) node pointer """ return node """ Function to count nodes in a binary search tree using Morris Inorder traversal""" def counNodes(root): # Initialise count of nodes as 0 count = 0 if (root == None): return count current = root while (current != None): if (current.left == None): # Count node if its left is None count+=1 # Move to its right current = current.right else: """ Find the inorder predecessor of current """ pre = current.left while (pre.right != None and pre.right != current): pre = pre.right """ Make current as right child of its inorder predecessor """ if(pre.right == None): pre.right = current current = current.left else: pre.right = None # Increment count if the current # node is to be visited count += 1 current = current.right return count """ Function to find median in O(n) time and O(1) space using Morris Inorder traversal""" def findMedian(root): if (root == None): return 0 count = counNodes(root) currCount = 0 current = root while (current != None): if (current.left == None): # count current node currCount += 1 # check if current node is the median # Odd case if (count % 2 != 0 and currCount == (count + 1)//2): return prev.data # Even case elif (count % 2 == 0 and currCount == (count//2)+1): return (prev.data + current.data)//2 # Update prev for even no. of nodes prev = current #Move to the right current = current.right else: """ Find the inorder predecessor of current """ pre = current.left while (pre.right != None and pre.right != current): pre = pre.right """ Make current as right child of its inorder predecessor """ if (pre.right == None): pre.right = current current = current.left else: pre.right = None prev = pre # Count current node currCount+= 1 # Check if the current node is the median if (count % 2 != 0 and currCount == (count + 1) // 2 ): return current.data elif (count%2 == 0 and currCount == (count // 2) + 1): return (prev.data+current.data)//2 # update prev node for the case of even # no. of nodes prev = current current = current.right # Driver Code if __name__ == '__main__': """ Constructed binary tree is 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = newNode(50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print("Median of BST is ",findMedian(root)) # This code is contributed # Shubham Singh(SHUBHAMSINGH10)
constant
linear
# Python program to find largest # BST in a Binary Tree. INT_MIN = -2147483648 INT_MAX = 2147483647 # Helper function that allocates a new # node with the given data and None left # and right pointers. class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Returns Information about subtree. The # Information also includes size of largest # subtree which is a BST def largestBSTBT(root): # Base cases : When tree is empty or it has # one child. if (root == None): return 0, INT_MIN, INT_MAX, 0, True if (root.left == None and root.right == None) : return 1, root.data, root.data, 1, True # Recur for left subtree and right subtrees l = largestBSTBT(root.left) r = largestBSTBT(root.right) # Create a return variable and initialize its # size. ret = [0, 0, 0, 0, 0] ret[0] = (1 + l[0] + r[0]) # If whole tree rooted under current root is # BST. if (l[4] and r[4] and l[1] < root.data and r[2] > root.data) : ret[2] = min(l[2], root.data) ret[1] = max(r[1], root.data) # Update answer for tree rooted under # current 'root' ret[3] = max(l[3], r[3]) + 1; ret[4] = True return ret # If whole tree is not BST, return maximum # of left and right subtrees ret[3] = max(l[3], r[3]) ret[4] = False return ret # Driver Code if __name__ == '__main__': """Let us construct the following Tree 60 / \ 65 70 / 50 """ root = newNode(60) root.left = newNode(65) root.right = newNode(70) root.left.left = newNode(50) print("Size of the largest BST is", largestBSTBT(root)[3]) # This code is contributed # Shubham Singh(SHUBHAMSINGH10) # Naman Sharma (NAMANSHARMA1805)
linear
linear
# Python3 program to remove BST keys # outside the given range # A BST node has key, and left and right # pointers. A utility function to create # a new BST node with key as given num class newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Removes all nodes having value outside # the given range and returns the root # of modified tree def removeOutsideRange(root, Min, Max): # Base Case if root == None: return None # First fix the left and right # subtrees of root root.left = removeOutsideRange(root.left, Min, Max) root.right = removeOutsideRange(root.right, Min, Max) # Now fix the root. There are 2 # possible cases for root # 1.a) Root's key is smaller than # min value (root is not in range) if root.key < Min: rChild = root.right return rChild # 1.b) Root's key is greater than max # value (root is not in range) if root.key > Max: lChild = root.left return lChild # 2. Root is in range return root # A utility function to insert a given # key to BST def insert(root, key): if root == None: return newNode(key) if root.key > key: root.left = insert(root.left, key) else: root.right = insert(root.right, key) return root # Utility function to traverse the binary # tree after conversion def inorderTraversal(root): if root: inorderTraversal( root.left) print(root.key, end = " ") inorderTraversal( root.right) # Driver Code if __name__ == '__main__': root = None root = insert(root, 6) root = insert(root, -13) root = insert(root, 14) root = insert(root, -8) root = insert(root, 15) root = insert(root, 13) root = insert(root, 7) print("Inorder traversal of the given tree is:", end = " ") inorderTraversal(root) root = removeOutsideRange(root, -10, 13) print() print("Inorder traversal of the modified tree is:", end = " ") inorderTraversal(root) # This code is contributed by PranchalK
constant
linear
# Python program to find BST keys in given range # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # The function prints all the keys in the given range # [k1..k2]. Assumes that k1 < k2 def Print(root, k1, k2): # Base Case if root is None: return # Since the desired o/p is sorted, recurse for left # subtree first. If root.data is greater than k1, then # only we can get o/p keys in left subtree if k1 < root.data : Print(root.left, k1, k2) # If root's data lies in range, then prints root's data if k1 <= root.data and k2 >= root.data: print (root.data,end=' ') # recursively call the right subtree Print(root.right, k1, k2) # Driver function to test above function k1 = 10 ; k2 = 25 ; root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(4) root.left.right = Node(12) Print(root, k1, k2) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
logn
linear
# Python3 code to print BST keys in given Range # in constant space using Morris traversal. # Helper function to create a new node class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to print the keys in range def RangeTraversal(root, n1, n2): if root == None: return curr = root while curr: if curr.left == None: # check if current node lies # between n1 and n2 if curr.data <= n2 and curr.data >= n1: print(curr.data, end = " ") curr = curr.right else: pre = curr.left # 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. while (pre.right != None and pre.right != curr): pre = pre.right if pre.right == None: pre.right = curr; curr = curr.left else: pre.right = None # check if current node lies # between n1 and n2 if curr.data <= n2 and curr.data >= n1: print(curr.data, end = " ") curr = curr.right # Driver Code if __name__ == '__main__': # Constructed binary tree is # 4 # / \ # 2 7 # / \ / \ # 1 3 6 10 root = newNode(4) root.left = newNode(2) root.right = newNode(7) root.left.left = newNode(1) root.left.right = newNode(3) root.right.left = newNode(6) root.right.right = newNode(10) RangeTraversal(root, 4, 12) # This code is contributed by PranchalK
constant
linear
# Python3 program to count BST nodes # within a given range # Utility function to create new node class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Returns count of nodes in BST in # range [low, high] def getCount(root, low, high): # Base case if root == None: return 0 # Special Optional case for improving # efficiency if root.data == high and root.data == low: return 1 # If current node is in range, then # include it in count and recur for # left and right children of it if root.data <= high and root.data >= low: return (1 + getCount(root.left, low, high) + getCount(root.right, low, high)) # If current node is smaller than low, # then recur for right child elif root.data < low: return getCount(root.right, low, high) # Else recur for left child else: return getCount(root.left, low, high) # Driver Code if __name__ == '__main__': # Let us construct the BST shown in # the above figure root = newNode(10) root.left = newNode(5) root.right = newNode(50) root.left.left = newNode(1) root.right.left = newNode(40) root.right.right = newNode(100) # Let us constructed BST shown in above example # 10 # / \ # 5 50 # / / \ # 1 40 100 l = 5 h = 45 print("Count of nodes between [", l, ", ", h,"] is ", getCount(root, l, h)) # This code is contributed by PranchalK
linear
constant
# Python3 program to find Sum Of All # Elements smaller than or equal to # Kth Smallest Element In BST INT_MAX = 2147483647 # Binary Tree Node """ utility that allocates a newNode with the given key """ class createNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # A utility function to insert a new # Node with given key in BST and also # maintain lcount ,Sum def insert(root, key) : # If the tree is empty, return a new Node if (root == None) : return createNode(key) # Otherwise, recur down the tree if (root.data > key) : root.left = insert(root.left, key) else if (root.data < key): root.right = insert(root.right, key) # return the (unchanged) Node pointer return root # function return sum of all element smaller # than and equal to Kth smallest element def ksmallestElementSumRec(root, k, count) : # Base cases if (root == None) : return 0 if (count[0] > k[0]) : return 0 # Compute sum of elements in left subtree res = ksmallestElementSumRec(root.left, k, count) if (count[0] >= k[0]) : return res # Add root's data res += root.data # Add current Node count[0] += 1 if (count[0] >= k[0]) : return res # If count is less than k, return # right subtree Nodes return res + ksmallestElementSumRec(root.right, k, count) # Wrapper over ksmallestElementSumRec() def ksmallestElementSum(root, k): count = [0] return ksmallestElementSumRec(root, k, count) # Driver Code if __name__ == '__main__': """ 20 / \ 8 22 / \ 4 12 / \ 10 14 """ root = None root = insert(root, 20) root = insert(root, 8) root = insert(root, 4) root = insert(root, 12) root = insert(root, 10) root = insert(root, 14) root = insert(root, 22) k = [3] print(ksmallestElementSum(root, k)) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10)
logn
constant
# Python3 program to find predecessor # and successor in a BST # A utility function to create a # new BST node class newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Function that finds predecessor and # successor of key in BST. def findPreSuc(root, pre, suc, key): if root == None: return # Search for given key in BST. while root != None: # If root is given key. if root.key == key: # the minimum value in right # subtree is predecessor. if root.right: suc[0] = root.right while suc[0].left: suc[0] = suc[0].left # the maximum value in left # subtree is successor. if root.left: pre[0] = root.left while pre[0].right: pre[0] = pre[0].right return # If key is greater than root, then # key lies in right subtree. Root # could be predecessor if left # subtree of key is null. elif root.key < key: pre[0] = root root = root.right # If key is smaller than root, then # key lies in left subtree. Root # could be successor if right # subtree of key is null. else: suc[0] = root root = root.left # A utility function to insert # a new node with given key in BST def insert(node, key): if node == None: return newNode(key) if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) return node # Driver Code if __name__ == '__main__': key = 65 # Key to be searched in BST # Let us create following BST # 50 # / \ # / \ # 30 70 # / \ / \ # / \ / \ # 20 40 60 80 root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) pre, suc = [None], [None] findPreSuc(root, pre, suc, key) if pre[0] != None: print("Predecessor is", pre[0].key) else: print("-1") if suc[0] != None: print("Successor is", suc[0].key) else: print("-1") # This code is contributed by PranchalK
constant
linear
# Python3 program to find a pair with # given sum using hashing import sys import math class Node: def __init__(self, data): self.data = data self.left = None self.right = None def insert(root, data): if root is None: return Node(data) if(data < root.data): root.left = insert(root.left, data) if(data > root.data): root.right = insert(root.right, data) return root def findPairUtil(root, summ, unsorted_set): if root is None: return False if findPairUtil(root.left, summ, unsorted_set): return True if unsorted_set and (summ-root.data) in unsorted_set: print("Pair is Found ({},{})".format(summ-root.data, root.data)) return True else: unsorted_set.add(root.data) return findPairUtil(root.right, summ, unsorted_set) def findPair(root, summ): unsorted_set = set() if(not findPairUtil(root, summ, unsorted_set)): print("Pair do not exist!") # Driver code if __name__ == '__main__': root = None root = insert(root, 15) root = insert(root, 10) root = insert(root, 20) root = insert(root, 8) root = insert(root, 12) root = insert(root, 16) root = insert(root, 25) root = insert(root, 10) summ = 28 findPair(root, summ) # This code is contributed by Vikash Kumar 37
linear
linear
# Python3 program to find pairs with given # sum such that one element of pair exists # in one BST and other in other BST. # A utility function to create a new # BST node with key as given num class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # A utility function to insert a # given key to BST def insert(root, key): if root == None: return newNode(key) if root.data > key: root.left = insert(root.left, key) else: root.right = insert(root.right, key) return root # store storeInorder traversal in # auxiliary array def storeInorder(ptr, vect): if ptr == None: return storeInorder(ptr.left, vect) vect.append(ptr.data) storeInorder(ptr.right, vect) # Function to find pair for given # sum in different bst # vect1[] --> stores storeInorder traversal # of first bst # vect2[] --> stores storeInorder traversal # of second bst def pairSumUtil(vect1, vect2, Sum): # Initialize two indexes to two # different corners of two lists. left = 0 right = len(vect2) - 1 # find pair by moving two corners. while left < len(vect1) and right >= 0: # If we found a pair if vect1[left] + vect2[right] == Sum: print("(", vect1[left], ",", vect2[right], "),", end = " ") left += 1 right -= 1 # If sum is more, move to higher # value in first lists. else if vect1[left] + vect2[right] < Sum: left += 1 # If sum is less, move to lower # value in second lists. else: right -= 1 # 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. def pairSum(root1, root2, Sum): # Store inorder traversals of # two BSTs in two lists. vect1 = [] vect2 = [] storeInorder(root1, vect1) storeInorder(root2, vect2) # Now the problem reduces to finding a # pair with given sum such that one # element is in vect1 and other is in vect2. pairSumUtil(vect1, vect2, Sum) # Driver Code if __name__ == '__main__': # first BST root1 = None root1 = insert(root1, 8) root1 = insert(root1, 10) root1 = insert(root1, 3) root1 = insert(root1, 6) root1 = insert(root1, 1) root1 = insert(root1, 5) root1 = insert(root1, 7) root1 = insert(root1, 14) root1 = insert(root1, 13) # second BST root2 = None root2 = insert(root2, 5) root2 = insert(root2, 18) root2 = insert(root2, 2) root2 = insert(root2, 1) root2 = insert(root2, 3) root2 = insert(root2, 4) Sum = 10 pairSum(root1, root2, Sum) # This code is contributed by PranchalK
linear
linear
# Recursive Python program to find key # closest to k in given Binary Search Tree. # Utility that allocates a new node with the # given key and NULL left and right pointers. class newnode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # 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 def maxDiffUtil(ptr, k, min_diff, min_diff_key): if ptr == None: return # If k itself is present if ptr.key == k: min_diff_key[0] = k return # update min_diff and min_diff_key by # checking current node value if min_diff > abs(ptr.key - k): min_diff = abs(ptr.key - k) min_diff_key[0] = ptr.key # if k is less than ptr->key then move # in left subtree else in right subtree if k < ptr.key: maxDiffUtil(ptr.left, k, min_diff, min_diff_key) else: maxDiffUtil(ptr.right, k, min_diff, min_diff_key) # Wrapper over maxDiffUtil() def maxDiff(root, k): # Initialize minimum difference min_diff, min_diff_key = 999999999999, [-1] # Find value of min_diff_key (Closest # key in tree with k) maxDiffUtil(root, k, min_diff, min_diff_key) return min_diff_key[0] # Driver Code if __name__ == '__main__': root = newnode(9) root.left = newnode(4) root.right = newnode(17) root.left.left = newnode(3) root.left.right = newnode(6) root.left.right.left = newnode(5) root.left.right.right = newnode(7) root.right.right = newnode(22) root.right.right.left = newnode(20) k = 18 print(maxDiff(root, k)) # This code is contributed by PranchalK
constant
constant
#User function Template for python3 IMIN = -2147483648 IMAX = 2147483647 def largestBst(root): if root==None: return IMAX,IMIN,0 if (root.left==None and root.right==None): return root.data,root.data,1 left=largestBst(root.left) right=largestBst(root.right) ans=[0,0,0] if left[1]<root.data and right[0]>root.data: ans[0]=min(left[0],right[0],root.data) ans[1]=max(right[1],left[1],root.data) ans[2]=1+left[2]+right[2] return ans ans[0]=IMIN ans[1]=IMAX ans[2]=max(left[2],right[2]) return ans def largestBstUtil(root): # Return the size of the largest sub-tree which is also a BST return largestBst(root)[2] # Driver Code Starts import sys sys.setrecursionlimit(1000000) from collections import deque # Tree Node class newNode: def __init__(self, val): self.right = None self.data = val self.left = None # Driver Code if __name__ == '__main__': """Let us construct the following Tree 50 / \ 75 45 / 40 """ root = newNode(50) root.left = newNode(75) root.right = newNode(45) root.left.left = newNode(40) print("Size of the largest BST is",largestBstUtil(root))
linear
linear
# Python3 program to add all greater values # in every node of BST # A utility function to create a # new BST node class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Recursive function to add all greater # values in every node def modifyBSTUtil(root, Sum): # Base Case if root == None: return # Recur for right subtree modifyBSTUtil(root.right, Sum) # Now Sum[0] has sum of nodes in right # subtree, add root.data to sum and # update root.data Sum[0] = Sum[0] + root.data root.data = Sum[0] # Recur for left subtree modifyBSTUtil(root.left, Sum) # A wrapper over modifyBSTUtil() def modifyBST(root): Sum = [0] modifyBSTUtil(root, Sum) # A utility function to do inorder # traversal of BST def inorder(root): if root != None: inorder(root.left) print(root.data, end =" ") inorder(root.right) # A utility function to insert a new node # with given data in BST def insert(node, data): # If the tree is empty, return a new node if node == None: return newNode(data) # Otherwise, recur down the tree if data <= node.data: node.left = insert(node.left, data) else: node.right = insert(node.right, data) # return the (unchanged) node pointer return node # Driver Code if __name__ == '__main__': # Let us create following BST # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) modifyBST(root) # print inorder traversal of the # modified BST inorder(root) # This code is contributed by PranchalK
constant
linear
# Python code to convert a sorted array # to a balanced Binary Search Tree # binary tree node class Node: def __init__(self, d): self.data = d self.left = None self.right = None # function to convert sorted array to a # balanced BST # input : sorted array of integers # output: root node of balanced BST def sortedArrayToBST(arr): if not arr: return None # find middle index mid = (len(arr)) // 2 # make the middle element the root root = Node(arr[mid]) # left subtree of root has all # values <arr[mid] root.left = sortedArrayToBST(arr[:mid]) # right subtree of root has all # values >arr[mid] root.right = sortedArrayToBST(arr[mid+1:]) return root # A utility function to print the preorder # traversal of the BST def preOrder(node): if not node: return print node.data, preOrder(node.left) preOrder(node.right) # driver program to test above function """ Constructed balanced BST is 4 / \ 2 6 / \ / \ 1 3 5 7 """ arr = [1, 2, 3, 4, 5, 6, 7] root = sortedArrayToBST(arr) print "PreOrder Traversal of constructed BST ", preOrder(root) # This code is contributed by Ishita Tripathi
logn
linear
""" Python3 program to check if a tree is height-balanced """ # A binary tree Node class Node: # Constructor to create a new Node def __init__(self, data): self.data = data self.left = None self.right = None # function to find height of binary tree def height(root): # base condition when binary tree is empty if root is None: return 0 return max(height(root.left), height(root.right)) + 1 # function to check if tree is height-balanced or not def isBalanced(root): # Base condition if root is None: return True # for left and right subtree height lh = height(root.left) rh = height(root.right) # allowed values for (lh - rh) are 1, -1, 0 if (abs(lh - rh) <= 1) and isBalanced( root.left) is True and isBalanced(root.right) is True: return True # if we reach here means tree is not # height-balanced tree return False # Driver function to test the above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.left.left = Node(8) if isBalanced(root): print("Tree is balanced") else: print("Tree is not balanced") # This code is contributed by Shweta Singh
linear
quadratic
# Python3 program to correct the BST # if two nodes are swapped class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Utility function to track the nodes # that we have to swap def correctBstUtil(root, first, middle, last, prev): if(root): # Recur for the left sub tree correctBstUtil(root.left, first, middle, last, prev) # If this is the first violation, mark these # two nodes as 'first and 'middle' if(prev[0] and root.key < prev[0].key): if(not first[0]): first[0] = prev[0] middle[0] = root else: # If this is the second violation, # mark this node as last last[0] = root prev[0] = root # Recur for the right subtree correctBstUtil(root.right, first, middle, last, prev) # A function to fix a given BST where # two nodes are swapped. This function # uses correctBSTUtil() to find out two # nodes and swaps the nodes to fix the BST def correctBst(root): # Followed four lines just for forming # an array with only index 0 filled # with None and we will update it accordingly. # we made it null so that we can fill # node data in them. first = [None] middle = [None] last = [None] prev = [None] # Setting arrays (having zero index only) # for capturing the required node correctBstUtil(root, first, middle, last, prev) # Fixing the two nodes if(first[0] and last[0]): # Swapping for first and last key values first[0].key, last[0].key = (last[0].key, first[0].key) elif(first[0] and middle[0]): # Swapping for first and middle key values first[0].key, middle[0].key = (middle[0].key, first[0].key) # else tree will be fine # Function to print inorder # traversal of tree def PrintInorder(root): if(root): PrintInorder(root.left) print(root.key, end = " ") PrintInorder(root.right) else: return # Driver code # 6 # / \ # 10 2 # / \ / \ # 1 3 7 12 # Following 7 lines are for tree formation root = Node(6) root.left = Node(10) root.right = Node(2) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(7) root.right.right = Node(12) # Printing inorder traversal of normal tree print("inorder traversal of normal tree") PrintInorder(root) print("") # Function call to do the task correctBst(root) # Printing inorder for corrected Bst tree print("") print("inorder for corrected BST") PrintInorder(root) # This code is contributed by rajutkarshai
linear
linear
# Python program to find ceil of a given value in BST # A Binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Function to find ceil of a given input in BST. If input # is more than the max key in BST, return -1 def ceil(root, inp): # Base Case if root == None: return -1 # We found equal key if root.key == inp: return root.key # If root's key is smaller, ceil must be in right subtree if root.key < inp: return ceil(root.right, inp) # Else, either left subtree or root has the ceil value val = ceil(root.left, inp) return val if val >= inp else root.key # Driver code if __name__ == '__main__': root = Node(8) root.left = Node(4) root.right = Node(12) root.left.left = Node(2) root.left.right = Node(6) root.right.left = Node(10) root.right.right = Node(14) for i in range(16): print "% d % d" % (i, ceil(root, i)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
logn
logn
# Python program to find Floor of a given value in BST # A Binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Function to find Floor of a given input in BST. If input # is more than the max key in BST, return -1 def Floor(root, inp): # Base Case if root == None: return -1 # We found equal key if root.key == inp: return root.key # If root's key is larger, Floor must be in left subtree if root.key > inp: return Floor(root.left, inp) # Else, either right subtree or root has the Floor value else: floor = Floor(root.right, inp) # exception for -1 because it is being returned in base case return floor if floor <= inp and floor != -1 else root.key # Driver code if __name__ == '__main__': root = Node(8) root.left = Node(4) root.right = Node(12) root.left.left = Node(2) root.left.right = Node(6) root.right.left = Node(10) root.right.right = Node(14) for i in range(16): print(i, Floor(root, i)) # This code is contributed by Shubham Singh
logn
logn
# Python3 program to find floor and # ceil of a given key in BST # A binary tree node has key, # . left child and right child class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Helper function to find floor and # ceil of a given key in BST def floorCeilBSTHelper(root, key): global floor, ceil while (root): if (root.data == key): ceil = root.data floor = root.data return if (key > root.data): floor = root.data root = root.right else: ceil = root.data root = root.left # 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; def floorCeilBST(root, key): global floor, ceil # Variables 'floor' and 'ceil' # are passed by reference floor = -1 ceil = -1 floorCeilBSTHelper(root, key) print(key, floor, ceil) # Driver code if __name__ == '__main__': floor, ceil = -1, -1 root = Node(8) root.left = Node(4) root.right = Node(12) root.left.left = Node(2) root.left.right = Node(6) root.right.left = Node(10) root.right.right = Node(14) for i in range(16): floorCeilBST(root, i) # This code is contributed by mohit kumar 29
constant
logn
# Python3 program of iterative traversal based # method to find common elements in two BSTs. # A utility function to create a new node class newNode: def __init__(self, key): self.key = key self.left = self.right = None # Function two print common elements # in given two trees def printCommon(root1, root2): # Create two stacks for two inorder # traversals s1 = [] s2 = [] while 1: # append the Nodes of first # tree in stack s1 if root1: s1.append(root1) root1 = root1.left # append the Nodes of second tree # in stack s2 elif root2: s2.append(root2) root2 = root2.left # Both root1 and root2 are NULL here elif len(s1) != 0 and len(s2) != 0: root1 = s1[-1] root2 = s2[-1] # If current keys in two trees are same if root1.key == root2.key: print(root1.key, end=" ") s1.pop(-1) s2.pop(-1) # move to the inorder successor root1 = root1.right root2 = root2.right elif root1.key < root2.key: # 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 s1.pop(-1) root1 = root1.right # root2 is set to NULL, because we need # new Nodes of tree 1 root2 = None elif root1.key > root2.key: s2.pop(-1) root2 = root2.right root1 = None # Both roots and both stacks are empty else: break # A utility function to do inorder traversal def inorder(root): if root: inorder(root.left) print(root.key, end=" ") inorder(root.right) # A utility function to insert a new Node # with given key in BST def insert(node, key): # If the tree is empty, return a new Node if node == None: return newNode(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) Node pointer return node # Driver Code if __name__ == '__main__': # Create first tree as shown in example root1 = None root1 = insert(root1, 5) root1 = insert(root1, 1) root1 = insert(root1, 10) root1 = insert(root1, 0) root1 = insert(root1, 4) root1 = insert(root1, 7) root1 = insert(root1, 9) # Create second tree as shown in example root2 = None root2 = insert(root2, 10) root2 = insert(root2, 7) root2 = insert(root2, 20) root2 = insert(root2, 4) root2 = insert(root2, 9) print("Tree 1 : ") inorder(root1) print() print("Tree 2 : ") inorder(root2) print() print("Common Nodes: ") printCommon(root1, root2) # This code is contributed by PranchalK
logn
linear
# An AVL Tree based Python program to # count inversion in an array # A utility function to get height of # the tree rooted with N def height(N): if N == None: return 0 return N.height # A utility function to size of the # tree of rooted with N def size(N): if N == None: return 0 return N.size # Helper function that allocates a new # Node with the given key and NULL left # and right pointers. class newNode: def __init__(self, key): self.key = key self.left = self.right = None self.height = self.size = 1 # A utility function to right rotate # subtree rooted with y def rightRotate(y): x = y.left T2 = x.right # Perform rotation x.right = y y.left = T2 # Update heights y.height = max(height(y.left), height(y.right)) + 1 x.height = max(height(x.left), height(x.right)) + 1 # Update sizes y.size = size(y.left) + size(y.right) + 1 x.size = size(x.left) + size(x.right) + 1 # Return new root return x # A utility function to left rotate # subtree rooted with x def leftRotate(x): y = x.right T2 = y.left # Perform rotation y.left = x x.right = T2 # Update heights x.height = max(height(x.left), height(x.right)) + 1 y.height = max(height(y.left), height(y.right)) + 1 # Update sizes x.size = size(x.left) + size(x.right) + 1 y.size = size(y.left) + size(y.right) + 1 # Return new root return y # Get Balance factor of Node N def getBalance(N): if N == None: return 0 return height(N.left) - height(N.right) # Inserts a new key to the tree rotted # with Node. Also, updates *result (inversion count) def insert(node, key, result): # 1. Perform the normal BST rotation if node == None: return newNode(key) if key < node.key: node.left = insert(node.left, key, result) # UPDATE COUNT OF GREATER ELEMENTS FOR KEY result[0] = result[0] + size(node.right) + 1 else: node.right = insert(node.right, key, result) # 2. Update height and size of this ancestor node node.height = max(height(node.left), height(node.right)) + 1 node.size = size(node.left) + size(node.right) + 1 # 3. Get the balance factor of this ancestor # node to check whether this node became # unbalanced balance = getBalance(node) # If this node becomes unbalanced, # then there are 4 cases # Left Left Case if (balance > 1 and key < node.left.key): return rightRotate(node) # Right Right Case if (balance < -1 and key > node.right.key): return leftRotate(node) # Left Right Case if balance > 1 and key > node.left.key: node.left = leftRotate(node.left) return rightRotate(node) # Right Left Case if balance < -1 and key < node.right.key: node.right = rightRotate(node.right) return leftRotate(node) # return the (unchanged) node pointer return node # The following function returns # inversion count in arr[] def getInvCount(arr, n): root = None # Create empty AVL Tree result = [0] # Initialize result # Starting from first element, insert all # elements one by one in an AVL tree. for i in range(n): # Note that address of result is passed # as insert operation updates result by # adding count of elements greater than # arr[i] on left of arr[i] root = insert(root, arr[i], result) return result[0] # Driver Code if __name__ == '__main__': arr = [8, 4, 2, 1] n = len(arr) print("Number of inversions count are :", getInvCount(arr, n)) # This code is contributed by PranchalK
linear
nlogn
# Python3 program to print leaf node from # preorder of binary search tree. # Binary Search def binarySearch(inorder, l, r, d): mid = (l + r) >> 1 if (inorder[mid] == d): return mid elif (inorder[mid] > d): return binarySearch(inorder, l, mid - 1, d) else: return binarySearch(inorder, mid + 1, r, d) # Function to print Leaf Nodes by doing # preorder traversal of tree using # preorder and inorder arrays. def leafNodesRec(preorder, inorder, l, r, ind, n): # If l == r, therefore no right or left subtree. # So, it must be leaf Node, print it. if(l == r): print(inorder[l], end = " ") ind[0] = ind[0] + 1 return # If array is out of bound, return. if (l < 0 or l > r or r >= n): return # Finding the index of preorder element # in inorder array using binary search. loc = binarySearch(inorder, l, r, preorder[ind[0]]) # Incrementing the index. ind[0] = ind[0] + 1 # Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, ind, n) # Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, ind, n) # Finds leaf nodes from # given preorder traversal. def leafNodes(preorder, n): # To store inorder traversal inorder = [0] * n # Copy the preorder into another array. for i in range(n): inorder[i] = preorder[i] # Finding the inorder by sorting the array. inorder.sort() # Point to the index in preorder. ind = [0] # Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, ind, n) # Driver Code preorder = [890, 325, 290, 530, 965] n = len(preorder) leafNodes(preorder, n) # This code is contributed # by SHUBHAMSINGH10
linear
nlogn
# Python3 program to find rank of an # element in a stream. class newNode: def __init__(self, data): self.data = data self.left = self.right = None self.leftSize = 0 # Inserting a new Node. def insert(root, data): if root is None: return newNode(data) # Updating size of left subtree. if data <= root.data: root.left = insert(root.left, data) root.leftSize += 1 else: root.right = insert(root.right, data) return root # Function to get Rank of a Node x. def getRank(root, x): # Step 1. if root.data == x: return root.leftSize # Step 2. if x < root.data: if root.left is None: return -1 else: return getRank(root.left, x) # Step 3. else: if root.right is None: return -1 else: rightSize = getRank(root.right, x) if rightSize == -1: # x not found in right sub tree, i.e. not found in stream return -1 else: return root.leftSize + 1 + rightSize # Driver code if __name__ == '__main__': arr = [5, 1, 4, 4, 5, 9, 7, 13, 3] n = len(arr) x = 4 root = None for i in range(n): root = insert(root, arr[i]) print("Rank of", x, "in stream is:", getRank(root, x)) x = 13 print("Rank of", x, "in stream is:", getRank(root, x)) x = 8 print("Rank of", x, "in stream is:", getRank(root, x)) # This code is contributed by PranchalK
linear
linear
# Python3 program to find rank of an # element in a stream. # Driver code if __name__ == '__main__': a = [5, 1, 14, 4, 15, 9, 7, 20, 11] key = 20 arraySize = len(a) count = 0 for i in range(arraySize): if a[i] <= key: count += 1 print("Rank of", key, "in stream is:", count - 1) # This code is contributed by PranchalK
constant
linear
# Python program to insert element in binary tree class newNode(): def __init__(self, data): self.key = data self.left = None self.right = None """ Inorder traversal of a binary tree""" def inorder(temp): if (not temp): return inorder(temp.left) print(temp.key,end = " ") inorder(temp.right) """function to insert element in binary tree """ def insert(temp,key): if not temp: root = newNode(key) return q = [] q.append(temp) # Do level order traversal until we find # an empty place. while (len(q)): temp = q[0] q.pop(0) if (not temp.left): temp.left = newNode(key) break else: q.append(temp.left) if (not temp.right): temp.right = newNode(key) break else: q.append(temp.right) # Driver code if __name__ == '__main__': root = newNode(10) root.left = newNode(11) root.left.left = newNode(7) root.right = newNode(9) root.right.left = newNode(15) root.right.right = newNode(8) print("Inorder traversal before insertion:", end = " ") inorder(root) key = 12 insert(root, key) print() print("Inorder traversal after insertion:", end = " ") inorder(root) # This code is contributed by SHUBHAMSINGH10
np
linear
# Python3 program to illustrate deletion in a Binary Tree # class to create a node with data, left child and right child. class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Inorder traversal of a binary tree def inorder(temp): if(not temp): return inorder(temp.left) print(temp.data, end=" ") inorder(temp.right) # function to delete the given deepest node (d_node) in binary tree def deleteDeepest(root, d_node): q = [] q.append(root) while(len(q)): temp = q.pop(0) if temp is d_node: temp = None return if temp.right: if temp.right is d_node: temp.right = None return else: q.append(temp.right) if temp.left: if temp.left is d_node: temp.left = None return else: q.append(temp.left) # function to delete element in binary tree def deletion(root, key): if root == None: return None if root.left == None and root.right == None: if root.key == key: return None else: return root key_node = None q = [] q.append(root) temp = None while(len(q)): temp = q.pop(0) if temp.data == key: key_node = temp if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) if key_node: x = temp.data deleteDeepest(root, temp) key_node.data = x return root # Driver code if __name__ == '__main__': root = Node(10) root.left = Node(11) root.left.left = Node(7) root.left.right = Node(12) root.right = Node(9) root.right.left = Node(15) root.right.right = Node(8) print("The tree before the deletion:") inorder(root) key = 11 root = deletion(root, key) print() print("The tree after the deletion;") inorder(root) # This code is contributed by Monika Anandan
linear
linear
# Python3 program to delete element in binary tree # class to create a node with data, left child and right child. class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Inorder traversal of a binary tree def inorder(temp): if(not temp): return inorder(temp.left) print(temp.data, end=" ") inorder(temp.right) def deletion(root, key): if(root == None): return None if(root.left == None and root.right == None): if(root.data == key): return None else: return root key_node = None temp = None last = None q = [] q.append(root) # Do level order traversal to find deepest # node(temp), node to be deleted (key_node) # and parent of deepest node(last) while(len(q)): temp = q.pop(0) if(temp.data == key): key_node = temp if(temp.left): last = temp # storing the parent node q.append(temp.left) if(temp.right): last = temp # storing the parent node q.append(temp.right) if(key_node != None): key_node.data = temp.data # replacing key_node's data to deepest node's data if(last.right == temp): last.right = None else: last.left = None return root # Driver code if __name__ == '__main__': root = Node(9) root.left = Node(2) root.left.left = Node(4) root.left.right = Node(7) root.right = Node(8) print("Inorder traversal before deletion : ", end="") inorder(root) key = 7 root = deletion(root, key) print() print("Inorder traversal after deletion : ", end="") inorder(root) # This code is contributed by Abhijeet Kumar(abhijeet19403)
linear
linear
# Python3 implementation of tree using array # numbering starting from 0 to n-1. tree = [None] * 10 def root(key): if tree[0] != None: print("Tree already had root") else: tree[0] = key def set_left(key, parent): if tree[parent] == None: print("Can't set child at", (parent * 2) + 1, ", no parent found") else: tree[(parent * 2) + 1] = key def set_right(key, parent): if tree[parent] == None: print("Can't set child at", (parent * 2) + 2, ", no parent found") else: tree[(parent * 2) + 2] = key def print_tree(): for i in range(10): if tree[i] != None: print(tree[i], end="") else: print("-", end="") print() # Driver Code root('A') set_right('C', 0) set_left('D', 1) set_right('E', 1) set_right('F', 2) print_tree() # This code is contributed by Gaurav Kumar Tailor
linear
logn
# Python3 program to check foldable binary tree # A binary tree node has data, # pointer to left child and a # pointer to right child class newNode: def __init__(self, d): self.data = d self.left = None self.right = None # Returns true if the given # tree is foldable def isFoldable(node): # base case if node == None: return true # convert left subtree to its mirror mirror(node.left) # Compare the structures of the right subtree and mirrored # left subtree res = isStructSame(node.left, node.right) # Get the original tree back mirror(node.left) return res def isStructSame(a, b): if a == None and b == None: return True if a != None and b != None and isStructSame(a.left, b.left) and isStructSame(a.right, b.right): return True return False def mirror(node): if node == None: return else: # do the subtrees mirror(node.left) mirror(node.right) # swap the pointers in this node temp = node.left node.left = node.right node.right = temp # Driver Code if __name__ == '__main__': ''' The constructed binary tree is 1 / \ 2 3 \ / 4 5 ''' root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.right.left = newNode(4) root.left.right = newNode(5) if isFoldable(root): print("tree is foldable") else: print("Tree is not foldable")
linear
linear
# Python3 program to check # foldable binary tree # Utility function to create a new # tree node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if the given tree can be folded def IsFoldable(root): if (root == None): return True return IsFoldableUtil(root.left, root.right) # A utility function that checks # if trees with roots as n1 and n2 # are mirror of each other def IsFoldableUtil(n1, n2): # If both left and right subtrees are NULL, # then return true if n1 == None and n2 == None: return True # If one of the trees is NULL and other is not, # then return false if n1 == None or n2 == None: return False # Otherwise check if left and # right subtrees are mirrors of # their counterparts d1 = IsFoldableUtil(n1.left, n2.right) d2 = IsFoldableUtil(n1.right, n2.left) return d1 and d2 # Driver code if __name__ == "__main__": """ The constructed binary tree is 1 / \ 2 3 \ / 4 5 """ root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.right = newNode(4) root.right.left = newNode(5) if IsFoldable(root): print("tree is foldable") else: print("tree is not foldable") # This code is contributed by # Anupam Baranwal(anupambaranwal)
linear
linear
# class to create a node with key, left child and right child. class Node: def __init__(self, key): self.key = key self.left = None self.right = None # Function to find whether the tree is foldable def isFoldable(root): # Queue to store visited nodes q = [] # Initially add the left and right nodes of root if root != None: q.append(root.left) q.append(root.right) while (len(q) != 0): # Remove the front 2 nodes to # check for None condition p = q.pop(0) r = q.pop(0) # If both are None, continue and check # the further elements if (p == None and r == None): continue # If one of them is not None, then return False if ((p == None and r != None) or (p != None and r == None)): return False ''' Insert in the same order: 1. left of left subtree 2. right of right subtree 3. right of left subtree 4. left of right subtree ''' q.append(p.left) q.append(r.right) q.append(p.right) q.append(r.left) # Only if the tree is foldable return True # Driver code # Insert data into the tree root = Node(1) root.left = Node(2) root.right = Node(3) root.right.left = Node(4) root.left.right = Node(5) # Function call if isFoldable(root): print("tree is foldable") else: print("tree is not foldable") # This code is contributed by mariuscristiancapatina
linear
linear
# Python program to evaluate expression tree # Class to represent the nodes of syntax tree class node: def __init__(self, value): self.left = None self.data = value self.right = None # This function receives a node of the syntax tree # and recursively evaluate it def evaluateExpressionTree(root): # empty tree if root is None: return 0 # leaf node if root.left is None and root.right is None: return int(root.data) # evaluate left tree left_sum = evaluateExpressionTree(root.left) # evaluate right tree right_sum = evaluateExpressionTree(root.right) # check which operation to apply if root.data == '+': return left_sum + right_sum elif root.data == '-': return left_sum - right_sum elif root.data == '*': return left_sum * right_sum else: return left_sum // right_sum # Driver function to test above problem if __name__ == '__main__': # creating a sample tree root = node('+') root.left = node('*') root.left.left = node('5') root.left.right = node('-4') root.right = node('-') root.right.left = node('100') root.right.right = node('20') print (evaluateExpressionTree(root)) root = None # creating a sample tree root = node('+') root.left = node('*') root.left.left = node('5') root.left.right = node('4') root.right = node('-') root.right.left = node('100') root.right.right = node('/') root.right.right.left = node('20') root.right.right.right = node('2') print (evaluateExpressionTree(root)) # This code is contributed by Harshit Sidhwa
constant
linear
# Python program to do inorder traversal without recursion # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Iterative function for inorder tree traversal def inOrder(root): # Set current to root of binary tree current = root stack = [] # initialize stack while True: # Reach the left most Node of the current Node if current is not None: # Place pointer to a tree node on the stack # before traversing the node's left subtree stack.append(current) current = current.left # BackTrack from the empty subtree and visit the Node # at the top of the stack; however, if the stack is # empty you are done elif(stack): current = stack.pop() print(current.data, end=" ") # Python 3 printing # We have visited the node and its left # subtree. Now, it's right subtree's turn current = current.right else: break print() # Driver program to test above function """ Constructed binary tree is 1 / \ 2 3 / \ 4 5 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) inOrder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
linear
"""Python3 program for finding postorder traversal of BST from preorder traversal""" INT_MIN = -2**31 INT_MAX = 2**31 # Function to find postorder traversal # from preorder traversal. def findPostOrderUtil(pre, n, minval, maxval, preIndex): # If entire preorder array is traversed # then return as no more element is left # to be added to post order array. if (preIndex[0] == n): return # If array element does not lie in # range specified, then it is not # part of current subtree. if (pre[preIndex[0]] < minval or pre[preIndex[0]] > maxval): return # Store current value, to be printed later, # after printing left and right subtrees. # Increment preIndex to find left and right # subtrees, and pass this updated value to # recursive calls. val = pre[preIndex[0]] preIndex[0] += 1 # All elements with value between minval # and val lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex) # All elements with value between val # and maxval lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex) print(val, end=" ") # Function to find postorder traversal. def findPostOrder(pre, n): # To store index of element to be # traversed next in preorder array. # This is passed by reference to # utility function. preIndex = [0] findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex) # Driver Code if __name__ == '__main__': pre = [40, 30, 35, 80, 100] n = len(pre) # Calling function findPostOrder(pre, n) # This code is contributed by # SHUBHAMSINGH10
linear
linear
# Recursive Python program for level # order traversal of Binary Tree # A node structure class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Function to print level order traversal of tree def printLevelOrder(root): h = height(root) for i in range(1, h+1): printCurrentLevel(root, i) # Print nodes at a current level def printCurrentLevel(root, level): if root is None: return if level == 1: print(root.data, end=" ") elif level > 1: printCurrentLevel(root.left, level-1) printCurrentLevel(root.right, level-1) """ Compute the height of a tree--the number of nodes along the longest path from the root node down to the farthest leaf node """ def height(node): if node is None: return 0 else: # Compute the height of each subtree lheight = height(node.left) rheight = height(node.right) # Use the larger one if lheight > rheight: return lheight+1 else: return rheight+1 # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Level order traversal of binary tree is -") printLevelOrder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
quadratic
# Python program to print level # order traversal using Queue # A node structure class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Iterative Method to print the # height of a binary tree def printLevelOrder(root): # Base Case if root is None: return # Create an empty queue # for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while(len(queue) > 0): # Print front of queue and # remove it from queue print(queue[0].data, end = " ") node = queue.pop(0) # Enqueue left child if node.left is not None: queue.append(node.left) # Enqueue right child if node.right is not None: queue.append(node.right) # Driver Program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Level Order Traversal of binary tree is -") printLevelOrder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
linear
# Python3 program for recursive level order # traversal in spiral form class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None """ Function to print spiral traversal of a tree""" def printSpiral(root): h = height(root) """ltr Left to Right. If this variable is set, then the given level is traversed from left to right. """ ltr = False for i in range(1, h + 1): printGivenLevel(root, i, ltr) """Revert ltr to traverse next level in opposite order""" ltr = not ltr """ Print nodes at a given level """ def printGivenLevel(root, level, ltr): if(root == None): return if(level == 1): print(root.data, end=" ") elif (level > 1): if(ltr): printGivenLevel(root.left, level - 1, ltr) printGivenLevel(root.right, level - 1, ltr) else: printGivenLevel(root.right, level - 1, ltr) printGivenLevel(root.left, level - 1, ltr) """ Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.""" def height(node): if (node == None): return 0 else: """ compute the height of each subtree """ lheight = height(node.left) rheight = height(node.right) """ use the larger one """ if (lheight > rheight): return(lheight + 1) else: return(rheight + 1) # Driver Code if __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(7) root.left.right = newNode(6) root.right.left = newNode(5) root.right.right = newNode(4) print("Spiral Order traversal of binary tree is") printSpiral(root) # This code is contributed # by SHUBHAMSINGH10
linear
quadratic
# Python3 implementation of a O(n) time # method for spiral order traversal # A class to create a new node class newNode: def __init__(self, data): self.data = data self.left = None self.right = None def printSpiral(root): if (root == None): return # None check # Create two stacks to store # alternate levels s1 = [] # For levels to be printed # from right to left s2 = [] # For levels to be printed # from left to right # append first level to first stack 's1' s1.append(root) # Keep printing while any of the # stacks has some nodes while not len(s1) == 0 or not len(s2) == 0: # Print nodes of current level from s1 # and append nodes of next level to s2 while not len(s1) == 0: temp = s1[-1] s1.pop() print(temp.data, end=" ") # Note that is right is appended # before left if (temp.right): s2.append(temp.right) if (temp.left): s2.append(temp.left) # Print nodes of current level from s2 # and append nodes of next level to s1 while (not len(s2) == 0): temp = s2[-1] s2.pop() print(temp.data, end=" ") # Note that is left is appended # before right if (temp.left): s1.append(temp.left) if (temp.right): s1.append(temp.right) # Driver Code if __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(7) root.left.right = newNode(6) root.right.left = newNode(5) root.right.right = newNode(4) print("Spiral Order traversal of", "binary tree is ") printSpiral(root) # This code is contributed by PranchalK
linear
linear
# Python3 implementation of above approach # A class to create a new node from collections import deque class newNode: def __init__(self, data): self.key = data self.left = None self.right = None def spiralPrint(root): # Declare a deque dq = deque() # Insert the root of the tree into the deque dq.append(root) # Create a variable that will switch in each iteration reverse = True # Start iteration while (len(dq)): # Save the size of the deque here itself, as in further steps the size # of deque will frequently change n = len(dq) # If we are printing left to right if(not reverse): # Iterate from left to right while (n > 0): n -= 1 # Insert the child from the back of the deque # Left child first if (dq[0].left != None): dq.append(dq[0].left) if (dq[0].right != None): dq.append(dq[0].right) # Print the current processed element print(dq[0].key, end=" ") dq.popleft() # Switch reverse for next traversal reverse = not reverse else: # If we are printing right to left # Iterate the deque in reverse order and insert the children # from the front while (n > 0): n -= 1 # Insert the child in the front of the deque # Right child first if (dq[-1].right != None): dq.appendleft(dq[-1].right) if (dq[-1].left != None): dq.appendleft(dq[-1].left) # Print the current processed element print(dq[-1].key, end=" ") dq.pop() # Switch reverse for next traversal reverse = not reverse # Driver Code if __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(7) root.left.right = newNode(6) root.right.left = newNode(5) root.right.right = newNode(4) print("Spiral Order traversal of", "binary tree is :") spiralPrint(root) # This code is contributed by Abhijeet Kumar(abhijeet19403)
linear
linear
# Python program for special order traversal # A binary tree node class Node: # A constructor for making a new node def __init__(self, key): self.data = key self.left = None self.right = None # Given a perfect binary tree print its node in # specific order def printSpecificLevelOrder(root): if root is None: return # Let us print root and next level first print (root.data,end=" ") # Since it is perfect Binary tree, # one of the node is needed to be checked if root.left is not None : print (root.left.data,end=" ") print (root.right.data,end=" ") # Do anything more if there are nodes at next level # in given perfect Binary Tree if root.left.left is None: return # Create a queue and enqueue left and right # children of root q = [] q.append(root.left) q.append(root.right) # We process two nodes at a time, so we need # two variables to store two front items of queue first = None second = None # Traversal loop while(len(q) > 0): # Pop two items from queue first = q.pop(0) second = q.pop(0) # Print children of first and second in reverse order print (first.left.data,end=" ") print (second.right.data,end=" ") print (first.right.data,end=" ") print (second.left.data,end=" ") # If first and second have grandchildren, # enqueue them in reverse order if first.left.left is not None: q.append(first.left) q.append(second.right) q.append(first.right) q.append(second.left) # Driver program to test above function # Perfect Binary Tree of Height 4 root = Node(1) root.left= Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.left.left.left = Node(8) root.left.left.right = Node(9) root.left.right.left = Node(10) root.left.right.right = Node(11) root.right.left.left = Node(12) root.right.left.right = Node(13) root.right.right.left = Node(14) root.right.right.right = Node(15) root.left.left.left.left = Node(16) root.left.left.left.right = Node(17) root.left.left.right.left = Node(18) root.left.left.right.right = Node(19) root.left.right.left.left = Node(20) root.left.right.left.right = Node(21) root.left.right.right.left = Node(22) root.left.right.right.right = Node(23) root.right.left.left.left = Node(24) root.right.left.left.right = Node(25) root.right.left.right.left = Node(26) root.right.left.right.right = Node(27) root.right.right.left.left = Node(28) root.right.right.left.right = Node(29) root.right.right.right.left = Node(30) root.right.right.right.right = Node(31) print ("Specific Level Order traversal of binary tree is") printSpecificLevelOrder(root); # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
linear
# Python3 program to reverse # alternate levels of a tree # A Binary Tree Node # Utility function to create # a new tree node class Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None def preorder(root1, root2, lvl): # Base cases if (root1 == None or root2 == None): return # Swap subtrees if level is even if (lvl % 2 == 0): t = root1.key root1.key = root2.key root2.key = t # Recur for left and right subtrees # (Note : left of root1 is passed and # right of root2 in first call and # opposite in second call. preorder(root1.left, root2.right, lvl + 1) preorder(root1.right, root2.left, lvl + 1) # This function calls preorder() # for left and right children of root def reverseAlternate(root): preorder(root.left, root.right, 0) # Inorder traversal (used to print # initial and modified trees) def printInorder(root): if (root == None): return printInorder(root.left) print( root.key, end = " ") printInorder(root.right) # A utility function to create a new node def newNode(key): temp = Node(' ') temp.left = temp.right = None temp.key = key return temp # Driver Code if __name__ == '__main__': root = newNode('a') root.left = newNode('b') root.right = newNode('c') root.left.left = newNode('d') root.left.right = newNode('e') root.right.left = newNode('f') root.right.right = newNode('g') root.left.left.left = newNode('h') root.left.left.right = newNode('i') root.left.right.left = newNode('j') root.left.right.right = newNode('k') root.right.left.left = newNode('l') root.right.left.right = newNode('m') root.right.right.left = newNode('n') root.right.right.right = newNode('o') print( "Inorder Traversal of given tree") printInorder(root) reverseAlternate(root) print("\nInorder Traversal of modified tree") printInorder(root) # This code is contributed by Arnab Kundu
logn
linear
# Python program to perform iterative preorder traversal # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # An iterative process to print preorder traversal of BT def iterativePreorder(root): # Base CAse if root is None: return # create an empty stack and push root to it nodeStack = [] nodeStack.append(root) # 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 */ while(len(nodeStack) > 0): # Pop the top item from stack and print it node = nodeStack.pop() print (node.data, end=" ") # Push right and left children of the popped node # to stack if node.right is not None: nodeStack.append(node.right) if node.left is not None: nodeStack.append(node.left) # Driver program to test above function root = Node(10) root.left = Node(8) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(5) root.right.left = Node(2) iterativePreorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
logn
linear
# Tree Node class Node: def __init__(self, data = 0): self.data = data self.left = None self.right = None # Iterative function to do Preorder traversal of the tree def preorderIterative(root): if (root == None): return st = [] # start from root node (set current node to root node) curr = root # run till stack is not empty or current is # not NULL while (len(st) or curr != None): # Print left children while exist # and keep appending right into the # stack. while (curr != None): print(curr.data, end = " ") if (curr.right != None): st.append(curr.right) curr = curr.left # We reach when curr is NULL, so We # take out a right child from stack if (len(st) > 0): curr = st[-1] st.pop() # Driver Code root = Node(10) root.left = Node(20) root.right = Node(30) root.left.left = Node(40) root.left.left.left = Node(70) root.left.right = Node(50) root.right.left = Node(60) root.left.left.right = Node(80) preorderIterative(root) # This code is contributed by Arnab Kundu
logn
linear
# Python program for diagonal # traversal of Binary Tree # A binary tree node class Node: # Constructor to create a # new binary tree node def __init__(self, data): self.data = data self.left = None self.right = None """ root - root of the binary tree d - distance of current line from rightmost -topmost slope. diagonalPrint - multimap to store Diagonal elements (Passed by Reference) """ def diagonalPrintUtil(root, d, diagonalPrintMap): # Base Case if root is None: return # Store all nodes of same line # together as a vector try : diagonalPrintMap[d].append(root.data) except KeyError: diagonalPrintMap[d] = [root.data] # Increase the vertical distance # if left child diagonalPrintUtil(root.left, d+1, diagonalPrintMap) # Vertical distance remains # same for right child diagonalPrintUtil(root.right, d, diagonalPrintMap) # Print diagonal traversal of given binary tree def diagonalPrint(root): # Create a dict to store diagonal elements diagonalPrintMap = dict() # Find the diagonal traversal diagonalPrintUtil(root, 0, diagonalPrintMap) print ("Diagonal Traversal of binary tree : ") for i in diagonalPrintMap: for j in diagonalPrintMap[i]: print (j,end=" ") print() # Driver Program root = Node(8) root.left = Node(3) root.right = Node(10) root.left.left = Node(1) root.left.right = Node(6) root.right.right = Node(14) root.right.right.left = Node(13) root.left.right.left = Node(4) root.left.right.right = Node(7) diagonalPrint(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
nlogn
from collections import deque # A binary tree node class Node: # Constructor to create a # new binary tree node def __init__(self, data): self.data = data self.left = None self.right = None def diagonal(root): out = [] node = root # queue to store left nodes left_q = deque() while node: # append data to output array out.append(node.data) # if left available add it to the queue if node.left: left_q.appendleft(node.left) # if right is available change the node if node.right: node = node.right else: # else pop the left_q if len(left_q) >= 1: node = left_q.pop() else: node = None return out # Driver Code root = Node(8) root.left = Node(3) root.right = Node(10) root.left.left = Node(1) root.left.right = Node(6) root.right.right = Node(14) root.right.right.left = Node(13) root.left.right.left = Node(4) root.left.right.right = Node(7) print(diagonal(root))
linear
nlogn
# Python Program to print diagonal traversal using queue # Tree Node class Node: def __init__(self, x): self.data = x self.left = None self.right = None def diagonalPrint(root): if root is None: return q = [] q.append(root) while len(q) > 0: size = len(q) answer = [] while size > 0: temp = q[0] q.pop(0) # traversing each component; while temp is not None: answer.append(temp.data) if temp.left is not None: q.append(temp.left) temp = temp.right size -= 1 result.append(answer) if __name__ == '__main__': root = Node(8) root.left = Node(3) root.right = Node(10) root.left.left = Node(1) root.left.right = Node(6) root.right.right = Node(14) root.right.right.left = Node(13) root.left.right.left = Node(4) root.left.right.right = Node(7) result = [] diagonalPrint(root) for i in range(len(result)): for j in range(len(result[i])): print(result[i][j], end=" ") print() # This code is contributed by Tapesh(tapeshdua420)
linear
linear
# Python3 program to print the diagonal traversal of binary tree class Node: def __init__(self, data): self.data = data self.left = None self.right = None #root node root=Node(0) # function to print in diagonal order def traverse(): # if the tree is empty, do not have to print # anything if root is None: return # if root is not empty, point curr node to the # root node curr = root # Maintain a queue to store left child q = [] # continue till the queue is empty and curr is null while(len(q)!=0 or curr != None): # if curr is not null # 1. print the data of the curr node # 2. if left child is present, add it to the queue # 3. Move curr pointer to the right if(curr != None): print(curr.data,end=" ") if(curr.left != None): q.append(curr.left) curr = curr.right # if curr is null, remove a node from the queue # and point it to curr node else: curr = q.pop(0) # Driver Code root = Node(8) root.left = Node(3) root.right = Node(10) root.left.left = Node(1) root.left.right = Node(6) root.right.right = Node(14) root.right.right.left = Node(13) root.left.right.left = Node(4) root.left.right.right = Node(7) traverse() # This code is contributed by Abhijeet Kumar(abhijeet19403)
linear
linear
# Python3 program to find density # of a binary tree # A binary tree node # Helper function to allocates a new node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Function to compute height and # size of a binary tree def heighAndSize(node, size): if (node == None) : return 0 # compute height of each subtree l = heighAndSize(node.left, size) r = heighAndSize(node.right, size) #increase size by 1 size[0] += 1 # return larger of the two return l + 1 if(l > r) else r + 1 # function to calculate density # of a binary tree def density(root): if (root == None) : return 0 size = [0] # To store size # Finds height and size _height = heighAndSize(root, size) return size[0] / _height # Driver Code if __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) print("Density of given binary tree is ", density(root)) # This code is contributed # by SHUBHAMSINGH10
logn
linear
#Python program to find height of full binary tree # using preorder # function to return max of left subtree height # or right subtree height def findDepthRec(tree, n, index) : if (index[0] >= n or tree[index[0]] == 'l'): return 0 # calc height of left subtree (In preorder # left subtree is processed before right) index[0] += 1 left = findDepthRec(tree, n, index) # calc height of right subtree index[0] += 1 right = findDepthRec(tree, n, index) return (max(left, right) + 1) # Wrapper over findDepthRec() def findDepth(tree, n) : index = [0] return findDepthRec(tree, n, index) # Driver program to test above functions if __name__ == '__main__': tree= "nlnnlll" n = len(tree) print(findDepth(tree, n)) # This code is contributed by SHUBHAMSINGH10
constant
linear
# Python code to modify binary tree for # traversal using only right pointer class newNode(): def __init__(self, data): self.data = data self.left = None self.right = None # Function to modify tree def modifytree(root): right = root.right rightMost = root # if the left tree exists if (root.left): # get the right-most of the # original left subtree rightMost = modifytree(root.left) # set root right to left subtree root.right = root.left root.left = None # if the right subtree does # not exists we are done! if (not right): return rightMost # set right pointer of right-most # of the original left subtree rightMost.right = right # modify the rightsubtree rightMost = modifytree(right) return rightMost # printing using right pointer only def printpre(root): while (root != None): print(root.data,end=" ") root = root.right # Driver code if __name__ == '__main__': """ Constructed binary tree is 10 / \ 8 2 / \ 3 5 """ root = newNode(10) root.left = newNode(8) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(5) modifytree(root) printpre(root) # This code is contributed by SHUBHAMSINGH10
linear
linear
# Python code to modify binary tree for # traversal using only right pointer # A binary tree node has data, # left child and right child class newNode(): def __init__(self, data): self.data = data self.left = None self.right = None # An iterative process to set the right # pointer of Binary tree def modifytree( root): # Base Case if (root == None): return # Create an empty stack and append root to it nodeStack = [] nodeStack.append(root) ''' Pop all items one by one. Do following for every popped item a) print b) append its right child c) append its left child Note that right child is appended first so that left is processed first ''' pre = None while (len(nodeStack)): # Pop the top item from stack node = nodeStack[-1] nodeStack.pop() # append right and left children of # the popped node to stack if (node.right): nodeStack.append(node.right) if (node.left): nodeStack.append(node.left) # check if some previous node exists if (pre != None): # set the right pointer of # previous node to current pre.right = node # set previous node as current node pre = node # printing using right pointer only def printpre( root): while (root != None): print(root.data, end = " ") root = root.right # Driver code ''' Constructed binary tree is 10 / \ 8 2 / \ 3 5 ''' root = newNode(10) root.left = newNode(8) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(5) modifytree(root) printpre(root) # This code is contributed by SHUBHAMSINGH10
linear
linear
# Python program to construct tree using inorder and # preorder traversals # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None """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 """ def buildTree(inOrder, preOrder, inStrt, inEnd): if (inStrt > inEnd): return None # Pick current node from Preorder traversal using # preIndex and increment preIndex tNode = Node(preOrder[buildTree.preIndex]) buildTree.preIndex += 1 # If this node has no children then return if inStrt == inEnd : return tNode # Else find the index of this node in Inorder traversal inIndex = search(inOrder, inStrt, inEnd, tNode.data) # Using index in Inorder Traversal, construct left # and right subtrees tNode.left = buildTree(inOrder, preOrder, inStrt, inIndex-1) tNode.right = buildTree(inOrder, preOrder, inIndex + 1, inEnd) return tNode # UTILITY FUNCTIONS # Function to find index of value in arr[start...end] # The function assumes that value is present in inOrder[] def search(arr, start, end, value): for i in range(start, end + 1): if arr[i] == value: return i def printInorder(node): if node is None: return # first recur on left child printInorder(node.left) # then print the data of node print (node.data,end=' ') # now recur on right child printInorder(node.right) # Driver program to test above function inOrder = ['D', 'B', 'E', 'A', 'F', 'C'] preOrder = ['A', 'B', 'D', 'E', 'C', 'F'] # Static variable preIndex buildTree.preIndex = 0 root = buildTree(inOrder, preOrder, 0, len(inOrder)-1) # Let us test the build tree by printing Inorder traversal print ("Inorder traversal of the constructed tree is") printInorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
quadratic
# Python3 program to construct tree using inorder # and preorder traversals # A binary tree node has data, pointer to left child # and a pointer to right child class Node: def __init__(self, x): self.data = x self.left = None self.right = None # 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 def buildTree(inn, pre, inStrt, inEnd): global preIndex, mp if (inStrt > inEnd): return None # Pick current node from Preorder traversal # using preIndex and increment preIndex curr = pre[preIndex] preIndex += 1 tNode = Node(curr) # If this node has no children then return if (inStrt == inEnd): return tNode # Else find the index of this # node in Inorder traversal inIndex = mp[curr] # Using index in Inorder traversal, # construct left and right subtress tNode.left = buildTree(inn, pre, inStrt, inIndex - 1) tNode.right = buildTree(inn, pre, inIndex + 1, inEnd) return tNode # This function mainly creates an # unordered_map, then calls buildTree() def buldTreeWrap(inn, pre, lenn): global mp # Store indexes of all items so that we # we can quickly find later # unordered_map<char, int> mp; for i in range(lenn): mp[inn[i]] = i return buildTree(inn, pre, 0, lenn - 1) # This function is here just to test buildTree() def printInorder(node): if (node == None): return printInorder(node.left) print(node.data, end = " ") printInorder(node.right) # Driver code if __name__ == '__main__': mp = {} preIndex = 0 inn = [ 'D', 'B', 'E', 'A', 'F', 'C' ] pre = [ 'A', 'B', 'D', 'E', 'C', 'F' ] lenn = len(inn) root = buldTreeWrap(inn, pre,lenn) # Let us test the built tree by printing # Inorder traversal print("Inorder traversal of " "the constructed tree is") printInorder(root) # This code is contributed by mohit kumar 29
linear
linear
# Python3 program to construct a tree using # inorder and preorder traversal class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None s = set() st = [] # Function to build tree using given traversal def buildTree(preorder, inorder, n): root = None; pre = 0 in_t = 0 while pre < n: node = None; while True: node = TreeNode(preorder[pre]) if (root == None): root = node; if (len(st) > 0): if (st[-1] in s): s.discard(st[-1]); st[-1].right = node; st.pop(); else: st[-1].left = node; st.append(node); if pre>=n or preorder[pre] == inorder[in_t]: pre += 1 break pre += 1 node = None; while (len(st) > 0 and in_t < n and st[-1].val == inorder[in_t]): node = st[-1]; st.pop(); in_t += 1 if (node != None): s.add(node); st.append(node); return root; # Function to print tree in_t Inorder def printInorder( node): if (node == None): return; ''' first recur on left child ''' printInorder(node.left); ''' then print data of node ''' print(node.val, end=" "); ''' now recur on right child ''' printInorder(node.right); # Driver code if __name__=='__main__': in_t = [ 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 ] pre = [ 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 ] l = len(in_t) root = buildTree(pre, in_t, l); printInorder(root); # This code is contributed by rutvik_56.
linear
linear
# Python program to construct tree using # inorder and level order traversals # A binary tree node class Node: # Constructor to create a new node def __init__(self, key): self.data = key self.left = None self.right = None """Recursive function to construct binary tree of size n from Inorder traversal ino[] and Level Order traversal level[]. The function doesn't do any error checking for cases where inorder and levelorder do not form a tree """ def buildTree(level, ino): # If ino array is not empty if ino: # Check if that element exist in level order for i in range(0, len(level)): if level[i] in ino: # Create a new node with # the matched element node = Node(level[i]) # Get the index of the matched element # in level order array io_index = ino.index(level[i]) break # Construct left and right subtree node.left = buildTree(level, ino[0:io_index]) node.right = buildTree(level, ino[io_index + 1:len(ino)]) return node else: return None def printInorder(node): if node is None: return # first recur on left child printInorder(node.left) # then print the data of node print(node.data, end=" ") # now recur on right child printInorder(node.right) # Driver code levelorder = [20, 8, 22, 4, 12, 10, 14] inorder = [4, 8, 10, 12, 14, 20, 22] ino_len = len(inorder) root = buildTree(levelorder, inorder) # Let us test the build tree by # printing Inorder traversal print("Inorder traversal of the constructed tree is") printInorder(root) # This code is contributed by 'Vaibhav Kumar'
linear
cubic
# Python program to create a Complete Binary Tree from # its linked list representation # Linked List node class ListNode: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # Binary Tree Node structure class BinaryTreeNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Class to convert the linked list to Binary Tree class Conversion: # Constructor for storing head of linked list # and root for the Binary Tree def __init__(self, data = None): self.head = None self.root = None def push(self, new_data): # Creating a new linked list node and storing data new_node = ListNode(new_data) # Make next of new node as head new_node.next = self.head # Move the head to point to new node self.head = new_node def convertList2Binary(self): # Queue to store the parent nodes q = [] # Base Case if self.head is None: self.root = None return # 1.) The first node is always the root node, # and add it to the queue self.root = BinaryTreeNode(self.head.data) q.append(self.root) # Advance the pointer to the next node self.head = self.head.next # Until the end of linked list is reached, do: while(self.head): # 2.a) Take the parent node from the q and # and remove it from q parent = q.pop(0) # Front of queue # 2.c) Take next two nodes from the linked list. # We will add them as children of the current # parent node in step 2.b. # Push them into the queue so that they will be # parent to the future node leftChild= None rightChild = None leftChild = BinaryTreeNode(self.head.data) q.append(leftChild) self.head = self.head.next if(self.head): rightChild = BinaryTreeNode(self.head.data) q.append(rightChild) self.head = self.head.next #2.b) Assign the left and right children of parent parent.left = leftChild parent.right = rightChild def inorderTraversal(self, root): if(root): self.inorderTraversal(root.left) print (root.data,end=" ") self.inorderTraversal(root.right) # Driver Program to test above function # Object of conversion class conv = Conversion() conv.push(36) conv.push(30) conv.push(25) conv.push(15) conv.push(12) conv.push(10) conv.convertList2Binary() print ("Inorder Traversal of the constructed Binary Tree is:") conv.inorderTraversal(conv.root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
np
linear
# Python3 program to construct binary # tree from given array in level # order fashion Tree Node # Helper function that allocates a #new node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Function to insert nodes in level order def insertLevelOrder(arr, i, n): root = None # Base case for recursion if i < n: root = newNode(arr[i]) # insert left child root.left = insertLevelOrder(arr, 2 * i + 1, n) # insert right child root.right = insertLevelOrder(arr, 2 * i + 2, n) return root # Function to print tree nodes in # InOrder fashion def inOrder(root): if root != None: inOrder(root.left) print(root.data,end=" ") inOrder(root.right) # Driver Code if __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6, 6, 6, 6] n = len(arr) root = None root = insertLevelOrder(arr, 0, n) inOrder(root) # This code is contributed by PranchalK and Improved by Thangaraj
linear
linear
# Python3 program for construction of # full binary tree # A binary tree node has data, pointer # to left child and a pointer to right child class Node: def __init__(self, data): self.data = data self.left = None self.right = None # 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[] def constructTreeUtil(pre: list, post: list, l: int, h: int, size: int) -> Node: global preIndex # Base case if (preIndex >= size or l > h): return None # The first node in preorder traversal # is root. So take the node at preIndex # from preorder and make it root, and # increment preIndex root = Node(pre[preIndex]) preIndex += 1 # If the current subarray has only # one element, no need to recur if (l == h or preIndex >= size): return root # Search the next element # of pre[] in post[] i = l while i <= h: if (pre[preIndex] == post[i]): break i += 1 # Use the index of element # found in postorder to divide # postorder array in two parts. # Left subtree and right subtree if (i <= h): root.left = constructTreeUtil(pre, post, l, i, size) root.right = constructTreeUtil(pre, post, i + 1, h-1, size) return root # The main function to construct # Full Binary Tree from given # preorder and postorder traversals. # This function mainly uses constructTreeUtil() def constructTree(pre: list, post: list, size: int) -> Node: global preIndex return constructTreeUtil(pre, post, 0, size - 1, size) # A utility function to print # inorder traversal of a Binary Tree def printInorder(node: Node) -> None: if (node is None): return printInorder(node.left) print(node.data, end = " ") printInorder(node.right) # Driver code if __name__ == "__main__": pre = [ 1, 2, 4, 8, 9, 5, 3, 6, 7 ] post = [ 8, 9, 4, 5, 2, 6, 7, 3, 1 ] size = len(pre) preIndex = 0 root = constructTree(pre, post, size) print("Inorder traversal of " "the constructed tree: ") printInorder(root) # This code is contributed by sanjeev2552
logn
constant
# Python3 program to construct full binary # tree using its preorder traversal and # preorder traversal of its mirror tree # Utility function to create a new tree node class newNode: def __init__(self,data): self.data = data self.left = self.right = None # A utility function to print inorder # traversal of a Binary Tree def printInorder(node): if (node == None) : return printInorder(node.left) print(node.data, end = " ") printInorder(node.right) # 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[] def constructBinaryTreeUtil(pre, preM, preIndex, l, h, size): # Base case if (preIndex >= size or l > h) : return None , preIndex # The first node in preorder traversal # is root. So take the node at preIndex # from preorder and make it root, and # increment preIndex root = newNode(pre[preIndex]) preIndex += 1 # If the current subarray has only # one element, no need to recur if (l == h): return root, preIndex # Search the next element of # pre[] in preM[] i = 0 for i in range(l, h + 1): if (pre[preIndex] == preM[i]): break # construct left and right subtrees # recursively if (i <= h): root.left, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, i, h, size) root.right, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, l + 1, i - 1, size) # return root return root, preIndex # function to construct full binary tree # using its preorder traversal and preorder # traversal of its mirror tree def constructBinaryTree(root, pre, preMirror, size): preIndex = 0 preMIndex = 0 root, x = constructBinaryTreeUtil(pre, preMirror, preIndex, 0, size - 1, size) Print Inorder(root) # Driver code if __name__ =="__main__": preOrder = [1, 2, 4, 5, 3, 6, 7] preOrderMirror = [1, 3, 7, 6, 2, 5, 4] size = 7 root = newNode(0) constructBinaryTree(root, preOrder, preOrderMirror, size) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10)
linear
quadratic
# key structure to store a binary tree node class Node: def __init__(self, key, left = None, right = None): self.key = key self.left = left self.right = right # Utility function to print binary tree nodes in-order fashion def inorder(node): if node: inorder(node.left) print(node.key, end = ' ') inorder(node.right) # Function to construct a binary tree # from specified ancestor matrix def constructBT(mat): # get number of rows in the matrix N = len(mat) # create an empty multi-dict dict = {} # Use sum as key and row numbers as values in the multi-dict for i in range(N): # find the sum of the current row total = sum(mat[i]) # insert the sum and row number into the dict dict.setdefault(total, []).append(i) # node[i] will store node for i in constructed tree node = [Node(-1)] * N last = 0 # the value of parent[i] is true if parent is set for i'th node parent = [False] * N # Traverse the dictionary in sorted order (default behavior) for key in dict.keys(): for row in dict.get(key): last = row # create a new node node[row] = Node(row) # if leaf node, do nothing if key == 0: continue # traverse row for i in range(N): # do if parent is not set and ancestor exits if not parent[i] and mat[row][i] == 1: # check for the unoccupied node if node[row].left is None: node[row].left = node[i] else: node[row].right = node[i] # set parent for i'th node parent[i] = True # last processed node is the root return node[last] # Construct a Binary Tree from Ancestor Matrix if __name__ == '__main__': mat = [[0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0]] root = constructBT(mat) inorder(root) # This code is contributed by Priyadarshini Kumari
quadratic
quadratic
# Python3 program to construct ancestor # matrix for given tree. class newnode: def __init__(self, data): self.data = data self.left = self.right = None # anc[] stores all ancestors of current node. # This function fills ancestors for all nodes. # It also returns size of tree. Size of tree # is used to print ancestor matrix. def ancestorMatrixRec(root, anc): global mat, MAX # base case if root == None: return 0 # Update all ancestors of current node data = root.data for i in range(len(anc)): mat[anc[i]][data] = 1 # Push data to list of ancestors anc.append(data) # Traverse left and right subtrees l = ancestorMatrixRec(root.left, anc) r = ancestorMatrixRec(root.right, anc) # Remove data from list the list of ancestors # as all descendants of it are processed now. anc.pop(-1) return l + r + 1 # This function mainly calls ancestorMatrixRec() def ancestorMatrix(root): # Create an empty ancestor array anc = [] # Fill ancestor matrix and find # size of tree. n = ancestorMatrixRec(root, anc) # Print the filled values for i in range(n): for j in range(n): print(mat[i][j], end = " ") print() # Driver Code MAX = 100 mat = [[0] * MAX for i in range(MAX)] # Construct the following binary tree # 5 # / \ # 1 2 # / \ / # 0 4 3 root = newnode(5) root.left = newnode(1) root.right = newnode(2) root.left.left = newnode(0) root.left.right = newnode(4) root.right.left = newnode(3) ancestorMatrix(root) # This code is contributed by PranchalK
quadratic
quadratic
# Python3 program to construct ancestor # matrix for given tree. size = 6 M = [[0 for j in range(size)] for i in range(size)] # A binary tree node class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Helper function to create a new node def newnode(data): temp = Node(data) return temp def printMatrix(): for i in range(size): for j in range(size): print(M[i][j], end = ' ') print() # First PreOrder Traversal def MatrixUtil(root, index): if (root == None): return preData = root.data # Since there is no ancestor for # root node, so we doesn't assign # it's value as 1 if (index == -1): index = root.data else: M[index][preData] = 1 MatrixUtil(root.left, preData) MatrixUtil(root.right, preData) def Matrix(root): # Call Func MatrixUtil MatrixUtil(root, -1) # Applying Transitive Closure # for the given Matrix for i in range(size): for j in range(size): for k in range(size): M[j][k] = (M[j][k] or (M[j][i] and M[i][k])) # Printing Matrix printMatrix() # Driver code if __name__=="__main__": root = newnode(5) root.left = newnode(1) root.right = newnode(2) root.left.left = newnode(0) root.left.right = newnode(4) root.right.left = newnode(3) Matrix(root) # This code is contributed by rutvik_56
quadratic
quadratic
# Python3 program to construct tree from # inorder traversal # Helper class that allocates a new node # with the given data and None left and # right pointers. class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # Prototypes of a utility function to get # the maximum value in inorder[start..end] # Recursive function to construct binary of # size len from Inorder traversal inorder[]. # Initial values of start and end should be # 0 and len -1. def buildTree (inorder, start, end): if start > end: return None # Find index of the maximum element # from Binary Tree i = Max (inorder, start, end) # Pick the maximum value and make it root root = newNode(inorder[i]) # If this is the only element in # inorder[start..end], then return it if start == end: return root # Using index in Inorder traversal, # construct left and right subtress root.left = buildTree (inorder, start, i - 1) root.right = buildTree (inorder, i + 1, end) return root # UTILITY FUNCTIONS # Function to find index of the maximum # value in arr[start...end] def Max(arr, strt, end): i, Max = 0, arr[strt] maxind = strt for i in range(strt + 1, end + 1): if arr[i] > Max: Max = arr[i] maxind = i return maxind # This function is here just to test buildTree() def printInorder (node): if node == None: return # first recur on left child printInorder (node.left) # then print the data of node print(node.data, end = " ") # now recur on right child printInorder (node.right) # Driver Code if __name__ == '__main__': # Assume that inorder traversal of # following tree is given # 40 # / \ # 10 30 # / \ #5 28 inorder = [5, 10, 40, 30, 28] Len = len(inorder) root = buildTree(inorder, 0, Len - 1) # Let us test the built tree by # printing Inorder traversal print("Inorder traversal of the", "constructed tree is ") printInorder(root) # This code is contributed by PranchalK
linear
quadratic
# Python3 program to construct tree using # inorder and postorder traversals # Helper function that allocates # a new node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Recursive function to construct binary # of size n from Inorder traversal in[] # and Postorder traversal post[]. Initial # values of inStrt and inEnd should be # 0 and n -1. The function doesn't do any # error checking for cases where inorder # and postorder do not form a tree def buildUtil(In, post, inStrt, inEnd, pIndex): # Base case if (inStrt > inEnd): return None # Pick current node from Postorder traversal # using postIndex and decrement postIndex node = newNode(post[pIndex[0]]) pIndex[0] -= 1 # If this node has no children # then return if (inStrt == inEnd): return node # Else find the index of this node # in Inorder traversal iIndex = search(In, inStrt, inEnd, node.data) # Using index in Inorder traversal, # construct left and right subtress node.right = buildUtil(In, post, iIndex + 1, inEnd, pIndex) node.left = buildUtil(In, post, inStrt, iIndex - 1, pIndex) return node # This function mainly initializes index # of root and calls buildUtil() def buildTree(In, post, n): pIndex = [n - 1] return buildUtil(In, post, 0, n - 1, pIndex) # Function to find index of value in # arr[start...end]. The function assumes # that value is postsent in in[] def search(arr, strt, end, value): i = 0 for i in range(strt, end + 1): if (arr[i] == value): break return i # This function is here just to test def preOrder(node): if node == None: return print(node.data,end=" ") preOrder(node.left) preOrder(node.right) # Driver code if __name__ == '__main__': In = [4, 8, 2, 5, 1, 6, 3, 7] post = [8, 4, 5, 2, 6, 7, 3, 1] n = len(In) root = buildTree(In, post, n) print("Preorder of the constructed tree :") preOrder(root) # This code is contributed by PranchalK
linear
quadratic
# Python3 program to construct tree using inorder # and postorder traversals # A binary tree node has data, pointer to left # child and a pointer to right child class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Recursive function to construct binary of size n # from Inorder traversal in[] and Postorder traversal # post[]. Initial values of inStrt and inEnd should # be 0 and n -1. The function doesn't do any error # checking for cases where inorder and postorder # do not form a tree def buildUtil(inn, post, innStrt, innEnd): global mp, index # Base case if (innStrt > innEnd): return None # Pick current node from Postorder traversal # using postIndex and decrement postIndex curr = post[index] node = Node(curr) index -= 1 # If this node has no children then return if (innStrt == innEnd): return node # Else find the index of this node inn # Inorder traversal iIndex = mp[curr] # Using index inn Inorder traversal, # construct left and right subtrees node.right = buildUtil(inn, post, iIndex + 1, innEnd) node.left = buildUtil(inn, post, innStrt, iIndex - 1) return node # This function mainly creates an unordered_map, # then calls buildTreeUtil() def buildTree(inn, post, lenn): global index # Store indexes of all items so that we # we can quickly find later for i in range(lenn): mp[inn[i]] = i # Index in postorder index = lenn - 1 return buildUtil(inn, post, 0, lenn - 1) # This function is here just to test def preOrder(node): if (node == None): return print(node.data, end = " ") preOrder(node.left) preOrder(node.right) # Driver Code if __name__ == '__main__': inn = [ 4, 8, 2, 5, 1, 6, 3, 7 ] post = [ 8, 4, 5, 2, 6, 7, 3, 1 ] n = len(inn) mp, index = {}, 0 root = buildTree(inn, post, n) print("Preorder of the constructed tree :") preOrder(root) # This code is contributed by mohit kumar 29
linear
linear
# Python program for above approach # A binary tree node has data, pointer # to left child and a pointer to right # child class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Tree building function def buildTree(inorder, post, n): # Create Stack of type Node st = [] # Create Set of type Node set = [] # Initialise postIndex with n - 1 postIndex = n - 1 # Initialise root with NULL root = None p = n-1 i = n-1 while p >= 0: # Initialise node with NULL node = None # Run loop while True: # initialize new node node = Node(post[p]) # check if root is equal to null if root == None: root = node # If size of set is greater than 0 if len(st) > 0: # If st top is present in the set s if st[-1] in set: set.remove(st[-1]) st[-1].left = node st.pop() else: st[-1].right = node st.append(node) p -= 1 if post[p+1] == inorder[i] or p < 0: break node = None # If the stack is not empty and st top data is equal to in[i] while len(st) > 0 and i >= 0 and st[-1].data == inorder[i]: node = st[-1] # Pop elements from stack st.pop() i -= 1 # if node not equal to None if node != None: set.append(node) st.append(node) # Return root return root # for print preOrder Traversal def preOrder(node): if node == None: return print(node.data, end=" ") preOrder(node.left) preOrder(node.right) # Driver Code if __name__ == '__main__': inorder = [4, 8, 2, 5, 1, 6, 3, 7] post = [8, 4, 5, 2, 6, 7, 3, 1] n = len(inorder) # Function Call root = buildTree(inorder, post, n) print("Preorder of the constructed tree :") # Function Call for preOrder preOrder(root) # This code is contributed by Tapesh(tapeshdua420)
linear
linear
# Python3 program to create a doubly linked # list out of given a ternary tree. # Custom node class. class newNode: def __init__(self, data): self.data = data self.left = None self.right = None self.middle = None class GFG: def __init__(self): # Tail of the linked list. self.tail = None # Function to push the node to the tail. def push(self, node): # To put the node at the end of # the already existing tail. self.tail.right = node # To point to the previous node. node.left = self.tail # Middle pointer should point to # nothing so null. initiate right # pointer to null. node.middle = node.right = None # Update the tail position. self.tail = node # Create a doubly linked list out of given # a ternary tree By traversing the tree in # preorder fashion. def ternaryTree(self, node, head): if node == None: return left = node.left middle = node.middle right = node.right if self.tail != node: # Already root is in the tail so dont push # the node when it was root.In the first # case both node and tail have root in them. self.push(node) # First the left child is to be taken. # Then middle and then right child. self.ternaryTree(left, head) self.ternaryTree(middle, head) self.ternaryTree(right, head) def startTree(self, root): # Initiate the head and tail with root. head = root self.tail = root self.ternaryTree(root, head) # Since the head,root are passed # with reference the changes in # root will be reflected in head. return head # Utility function for printing double linked list. def printList(self, head): print("Created Double Linked list is:") while head: print(head.data, end = " ") head = head.right # Driver code if __name__ == '__main__': # Constructing ternary tree as shown # in above figure root = newNode(30) root.left = newNode(5) root.middle = newNode(11) root.right = newNode(63) root.left.left = newNode(1) root.left.middle = newNode(4) root.left.right = newNode(8) root.middle.left = newNode(6) root.middle.middle = newNode(7) root.middle.right = newNode(15) root.right.left = newNode(31) root.right.middle = newNode(55) root.right.right = newNode(65) # The function which initiates the list # process returns the head. head = None gfg = GFG() head = gfg.startTree(root) gfg.printList(head) # This code is contributed by Winston Sebastian Pais
linear
linear
# Python3 program to create a tree with # left child right sibling representation from collections import deque class Node: def __init__(self, x): self.data = x self.next = None self.child = None # Adds a sibling to a list with # starting with n def addSibling(n, data): if (n == None): return None while (n.next): n = n.next n.next = Node(data) return n # Add child Node to a Node def addChild(n, data): if (n == None): return None # Check if child list is not empty if (n.child): return addSibling(n.child, data) else: n.child = Node(data) return n # Traverses tree in level order def traverseTree(root): # Corner cases if (root == None): return print(root.data, end = " ") if (root.child == None): return # Create a queue and enqueue root q = deque() curr = root.child q.append(curr) while (len(q) > 0): # Take out an item from the queue curr = q.popleft() #q.pop() # Print next level of taken out # item and enqueue next level's children while (curr != None): print(curr.data, end = " ") if (curr.child != None): q.append(curr.child) curr = curr.next # Driver code if __name__ == '__main__': root = Node(10) n1 = addChild(root, 2) n2 = addChild(root, 3) n3 = addChild(root, 4) n4 = addChild(n3, 6) n5 = addChild(root, 5) n6 = addChild(n5, 7) n7 = addChild(n5, 8) n8 = addChild(n5, 9) traverseTree(root) # This code is contributed by mohit kumar 29
linear
linear
# Python3 program to conStruct a # binary tree from the given String # Helper class that allocates a new node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # This function is here just to test def preOrder(node): if (node == None): return print(node.data, end=' ') preOrder(node.left) preOrder(node.right) # function to return the index of # close parenthesis def findIndex(Str, si, ei): if (si > ei): return -1 # Inbuilt stack s = [] for i in range(si, ei + 1): # if open parenthesis, push it if (Str[i] == '('): s.append(Str[i]) # if close parenthesis elif (Str[i] == ')'): if (s[-1] == '('): s.pop(-1) # if stack is empty, this is # the required index if len(s) == 0: return i # if not found return -1 return -1 # function to conStruct tree from String def treeFromString(Str, si, ei): # Base case if (si > ei): return None # new root root = newNode(ord(Str[si]) - ord('0')) index = -1 # if next char is '(' find the # index of its complement ')' if (si + 1 <= ei and Str[si + 1] == '('): index = findIndex(Str, si + 1, ei) # if index found if (index != -1): # call for left subtree root.left = treeFromString(Str, si + 2, index - 1) # call for right subtree root.right = treeFromString(Str, index + 2, ei - 1) return root # Driver Code if __name__ == '__main__': Str = "4(2(3)(1))(6(5))" root = treeFromString(Str, 0, len(Str) - 1) preOrder(root) # This code is contributed by pranchalK
linear
quadratic
# A simple inorder traversal based program to convert a # Binary Tree to DLL # A Binary Tree node class Node: # Constructor to create a new tree node def __init__(self, data): self.data = data self.left = None self.right = None # Standard Inorder traversal of tree def inorder(root): if root is not None: inorder(root.left) print ("\t%d" %(root.data),end=" ") inorder(root.right) # Changes left pointers to work as previous pointers # in converted DLL # The function simply does inorder traversal of # Binary Tree and updates # left pointer using previously visited node def fixPrevPtr(root): if root is not None: fixPrevPtr(root.left) root.left = fixPrevPtr.pre fixPrevPtr.pre = root fixPrevPtr(root.right) # Changes right pointers to work as next pointers in # converted DLL def fixNextPtr(root): prev = None # Find the right most node in BT or last node in DLL while(root and root.right != None): root = root.right # Start from the rightmost node, traverse back using # left pointers # While traversing, change right pointer of nodes while(root and root.left != None): prev = root root = root.left root.right = prev # The leftmost node is head of linked list, return it return root # The main function that converts BST to DLL and returns # head of DLL def BTToDLL(root): # Set the previous pointer fixPrevPtr(root) # Set the next pointer and return head of DLL return fixNextPtr(root) # Traversses the DLL from left to right def printList(root): while(root != None): print ("\t%d" %(root.data),end=" ") root = root.right # Driver program to test above function root = Node(10) root.left = Node(12) root.right = Node(15) root.left.left = Node(25) root.left.right = Node(30) root.right.left = Node(36) print ("Inorder Tree Traversal") inorder(root) # Static variable pre for function fixPrevPtr fixPrevPtr.pre = None head = BTToDLL(root) print ("\nDLL Traversal") printList(head) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
linear
linear
# Python3 program to convert a given Binary Tree to Doubly Linked List class Node: def __init__(self, data): self.data = data self.left = self.right = None class BinaryTree: # A simple recursive function to convert a given # Binary tree to Doubly Linked List # root --> Root of Binary Tree # head --> Pointer to head node of created doubly linked list root, head = None, None def BToDll(self, root: Node): if root is None: return # Recursively convert right subtree self.BToDll(root.right) # Insert root into doubly linked list root.right = self.head # Change left pointer of previous head if self.head is not None: self.head.left = root # Change head of doubly linked list self.head = root # Recursively convert left subtree self.BToDll(root.left) @staticmethod def print_list(head: Node): print('Extracted Double Linked list is:') while head is not None: print(head.data, end = ' ') head = head.right # Driver program to test above function if __name__ == '__main__': """ Constructing below tree 5 // \\ 3 6 // \\ \\ 1 4 8 // \\ // \\ 0 2 7 9 """ tree = BinaryTree() tree.root = Node(5) tree.root.left = Node(3) tree.root.right = Node(6) tree.root.left.left = Node(1) tree.root.left.right = Node(4) tree.root.right.right = Node(8) tree.root.left.left.left = Node(0) tree.root.left.left.right = Node(2) tree.root.right.right.left = Node(7) tree.root.right.right.right = Node(9) tree.BToDll(tree.root) tree.print_list(tree.head) # This code is contributed by Rajat Srivastava
linear
linear
# Python3 program to convert a tree # into its sum tree # Node definition class node: def __init__(self, data): self.left = None self.right = None self.data = data # Convert a given tree to a tree where # every node contains sum of values of # nodes in left and right subtrees # in the original tree def toSumTree(Node) : # Base case if(Node == None) : return 0 # Store the old value old_val = Node.data # Recursively call for left and # right subtrees and store the sum as # new value of this node Node.data = toSumTree(Node.left) + \ toSumTree(Node.right) # Return the sum of values of nodes # in left and right subtrees and # old_value of this node return Node.data + old_val # A utility function to print # inorder traversal of a Binary Tree def printInorder(Node) : if (Node == None) : return printInorder(Node.left) print(Node.data, end = " ") printInorder(Node.right) # Utility function to create a new Binary Tree node def newNode(data) : temp = node(0) temp.data = data temp.left = None temp.right = None return temp # Driver Code if __name__ == "__main__": root = None x = 0 # Constructing tree given in the above figure root = newNode(10) root.left = newNode(-2) root.right = newNode(6) root.left.left = newNode(8) root.left.right = newNode(-4) root.right.left = newNode(7) root.right.right = newNode(5) toSumTree(root) # Print inorder traversal of the converted # tree to test result of toSumTree() print("Inorder Traversal of the resultant tree is: ") printInorder(root) # This code is contributed by Arnab Kundu
constant
constant
# Python3 program to store sum of nodes # in left subtree in every node # Binary Tree Node # utility that allocates a new Node # with the given key class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Function to modify a Binary Tree so # that every node stores sum of values # in its left child including its own value def updatetree(root): # Base cases if (not root): return 0 if (root.left == None and root.right == None) : return root.data # Update left and right subtrees leftsum = updatetree(root.left) rightsum = updatetree(root.right) # Add leftsum to current node root.data += leftsum # Return sum of values under root return root.data + rightsum # Utility function to do inorder traversal def inorder(node) : if (node == None) : return inorder(node.left) print(node.data, end = " ") inorder(node.right) # Driver Code if __name__ == '__main__': """ Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 """ root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) updatetree(root) print("Inorder traversal of the modified tree is") inorder(root) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10)
linear
linear
# Python3 program to convert a binary # tree to its mirror # Utility function to create a new # tree node class newNode: def __init__(self, data): self.data = data self.left = self.right = None """ Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1 """ def mirror(node): if (node == None): return else: temp = node """ do the subtrees """ mirror(node.left) mirror(node.right) """ swap the pointers in this node """ temp = node.left node.left = node.right node.right = temp """ Helper function to print Inorder traversal.""" def inOrder(node): if (node == None): return inOrder(node.left) print(node.data, end=" ") inOrder(node.right) # Driver code if __name__ == "__main__": root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) """ Print inorder traversal of the input tree """ print("Inorder traversal of the", "constructed tree is") inOrder(root) """ Convert tree to its mirror """ mirror(root) """ Print inorder traversal of the mirror tree """ print("\nInorder traversal of", "the mirror tree is ") inOrder(root) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10)
linear
linear
# Python3 program to convert a Binary # Tree to its mirror # 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 class newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1 ''' def mirror(root): if (root == None): return q = [] q.append(root) # Do BFS. While doing BFS, keep swapping # left and right children while (len(q)): # pop top node from queue curr = q[0] q.pop(0) # swap left child with right child curr.left, curr.right = curr.right, curr.left # append left and right children if (curr.left): q.append(curr.left) if (curr.right): q.append(curr.right) """ Helper function to print Inorder traversal.""" def inOrder(node): if (node == None): return inOrder(node.left) print(node.data, end=" ") inOrder(node.right) # Driver code root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) """ Print inorder traversal of the input tree """ print("Inorder traversal of the constructed tree is") inOrder(root) """ Convert tree to its mirror """ mirror(root) """ Print inorder traversal of the mirror tree """ print("\nInorder traversal of the mirror tree is") inOrder(root) # This code is contributed by SHUBHAMSINGH10
linear
linear
# Python3 program to convert Binary Tree # into Doubly Linked List where the nodes # are represented spirally. # Binary tree node class newNode: # Constructor to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None """ Given a reference to the head of a list and a node, inserts the node on the front of the list. """ def push(head_ref, node): # Make right of given node as # head and left as None node.right = (head_ref) node.left = None # change left of head node to # given node if ((head_ref) != None): (head_ref).left = node # move the head to point to # the given node (head_ref) = node # Function to prints contents of DLL def printList(node): i = 0 while (i < len(node)): print(node[i].data, end = " ") i += 1 """ Function to print corner node at each level """ def spiralLevelOrder(root): # Base Case if (root == None): return # Create an empty deque for doing spiral # level order traversal and enqueue root q = [] q.append(root) # create a stack to store Binary # Tree nodes to insert into DLL later stk = [] level = 0 while (len(q)): # nodeCount indicates number of # Nodes at current level. nodeCount = len(q) # Dequeue all Nodes of current level # and Enqueue all Nodes of next level if (level&1): # odd level while (nodeCount > 0): # dequeue node from front & # push it to stack node = q[0] q.pop(0) stk.append(node) # insert its left and right children # in the back of the deque if (node.left != None): q.append(node.left) if (node.right != None): q.append(node.right) nodeCount -= 1 else: # even level while (nodeCount > 0): # dequeue node from the back & # push it to stack node = q[-1] q.pop(-1) stk.append(node) # inserts its right and left # children in the front of # the deque if (node.right != None): q.insert(0, node.right) if (node.left != None): q.insert(0, node.left) nodeCount -= 1 level += 1 # head pointer for DLL head = [] # pop all nodes from stack and push # them in the beginning of the list while (len(stk)): head.append(stk[0]) stk.pop(0) print("Created DLL is:") printList(head) # Driver Code if __name__ == '__main__': """Let us create Binary Tree as shown in above example """ root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.left.left = newNode(8) root.left.left.right = newNode(9) root.left.right.left = newNode(10) root.left.right.right = newNode(11) #root.right.left.left = newNode(12) root.right.left.right = newNode(13) root.right.right.left = newNode(14) #root.right.right.right = newNode(15) spiralLevelOrder(root) # This code is contributed # by SHUBHAMSINGH10
linear
linear
// C Program to convert a Binary Tree // to a Circular Doubly Linked List #include <stdio.h> #include <stdlib.h> // To represents a node of a Binary Tree typedef struct Node { struct Node *left, *right; int data; } Node; // A function that appends rightList at the end // of leftList. Node* concatenate(Node* leftList, Node* rightList) { // If either of the list is empty // then return the other list if (leftList == NULL) return rightList; if (rightList == NULL) return leftList; // Store the last Node of left List Node* leftLast = leftList->left; // Store the last Node of right List Node* rightLast = rightList->left; // Connect the last node of Left List // with the first Node of the right List leftLast->right = rightList; rightList->left = leftLast; // Left of first node points to // the last node in the list leftList->left = rightLast; // Right of last node refers to the first // node of the List rightLast->right = leftList; return leftList; } // Function converts a tree to a circular Linked List // and then returns the head of the Linked List Node* bTreeToCList(Node* root) { if (root == NULL) return NULL; // Recursively convert left and right subtrees Node* left = bTreeToCList(root->left); Node* right = bTreeToCList(root->right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root->left = root->right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List void displayCList(Node* head) { printf("Circular Linked List is :\n"); Node* itr = head; do { printf("%d ", itr->data); itr = itr->right; } while (head != itr); printf("\n"); } // Create a new Node and return its address Node* newNode(int data) { Node* temp = (Node*)malloc(sizeof(Node)); temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver Program to test above function int main() { Node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); Node* head = bTreeToCList(root); displayCList(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
logn
linear
# Python3 Program to convert a Binary # Tree to a Circular Doubly Linked List class newNode: def __init__(self, data): self.data = data self.left = self.right = None # A function that appends rightList # at the end of leftList. def concatenate(leftList, rightList): # If either of the list is empty # then return the other list if (leftList == None): return rightList if (rightList == None): return leftList # Store the last Node of left List leftLast = leftList.left # Store the last Node of right List rightLast = rightList.left # Connect the last node of Left List # with the first Node of the right List leftLast.right = rightList rightList.left = leftLast # Left of first node points to # the last node in the list leftList.left = rightLast # Right of last node refers to # the first node of the List rightLast.right = leftList return leftList # Function converts a tree to a circular # Linked List and then returns the head # of the Linked List def bTreeToCList(root): if (root == None): return None # Recursively convert left and # right subtrees left = bTreeToCList(root.left) right = bTreeToCList(root.right) # Make a circular linked list of single # node (or root). To do so, make the # right and left pointers of this node # point to itself root.left = root.right = root # Step 1 (concatenate the left list # with the list with single # node, i.e., current node) # Step 2 (concatenate the returned list # with the right List) return concatenate(concatenate(left, root), right) # Display Circular Link List def displayCList(head): print("Circular Linked List is :") itr = head first = 1 while (head != itr or first): print(itr.data, end=" ") itr = itr.right first = 0 print() # Driver Code if __name__ == '__main__': root = newNode(10) root.left = newNode(12) root.right = newNode(15) root.left.left = newNode(25) root.left.right = newNode(30) root.right.left = newNode(36) head = bTreeToCList(root) displayCList(head) # This code is contributed by PranchalK
logn
linear
# Class to define a node # structure of the tree class Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to convert ternary # expression to a Binary tree # It returns the root node # of the tree def convert_expression(expression, i): if i >= len(expression): return None # Create a new node object # for the expression at # ith index root = Node(expression[i]) i += 1 # if current character of # ternary expression is '?' # then we add next character # as a left child of # current node if (i < len(expression) and expression[i] is "?"): root.left = convert_expression(expression, i + 1) # else we have to add it # as a right child of # current node expression[0] == ':' elif i < len(expression): root.right = convert_expression(expression, i + 1) return root # Function to print the tree # in a pre-order traversal pattern def print_tree(root): if not root: return print(root.data, end=' ') print_tree(root.left) print_tree(root.right) # Driver Code if __name__ == "__main__": string_expression = "a?b?c:d:e" root_node = convert_expression(string_expression, 0) print_tree(root_node) # This code is contributed # by Kanav Malhotra
linear
linear
# Python3 program for Minimum swap required # to convert binary tree to binary search tree # Inorder Traversal of Binary Tree def inorder(a, n, index): global v # If index is greater or equal to # vector size if (index >= n): return inorder(a, n, 2 * index + 1) # Push elements in vector v.append(a[index]) inorder(a, n, 2 * index + 2) # Function to find minimum swaps # to sort an array def minSwaps(): global v t = [[0, 0] for i in range(len(v))] ans = -2 for i in range(len(v)): t[i][0], t[i][1] = v[i], i t, i = sorted(t), 0 while i < len(t): # break # second element is equal to i if (i == t[i][1]): i += 1 continue else: # Swapping of elements t[i][0], t[t[i][1]][0] = t[t[i][1]][0], t[i][0] t[i][1], t[t[i][1]][1] = t[t[i][1]][1], t[i][1] # Second is not equal to i if (i == t[i][1]): i -= 1 i += 1 ans += 1 return ans # Driver Code if __name__ == '__main__': v = [] a = [ 5, 6, 7, 8, 9, 10, 11 ] n = len(a) inorder(a, n, 0) print(minSwaps()) # This code is contributed by mohit kumar 29
linear
nlogn