Category Archives: Trees

BK-Tree | Introduction & Implementation

BK Tree or Burkhard Keller Tree is a data structure that is used to perform spell check based on Edit Distance (Levenshtein distance) concept. BK trees are also used for approximate string matching. Various auto correct feature in many softwares can be implemented based on this data structure. Pre-requisites : Edit distance Problem Metric tree… Read More »

Palindromic Tree | Introduction & Implementation

We encounter various problems like Maximum length palindrome in a string, number of palindromic substrings and many more interesting problems on palindromic substrings . Mostly of these palindromic substring problems have some DP O(n2) solution (n is length of the given string) or then we have a complex algorithm like Manacher’s algorithm which solves the… Read More »

Maximum edge removal from tree to make even forest

Given an undirected tree which has even number of vertices, we need to remove the maximum number of edges from this tree such that each connected component of the resultant forest has an even number of vertices. Examples: In above shown tree, we can remove at max 2 edges 0-2 and 0-4 shown in red… Read More »

Longest path in an undirected tree

Given an undirected tree, we need to find the longest path of this tree where a path is defined as a sequence of nodes. Example: Input : Below shown Tree using adjacency list representation: Output : 5 In below tree longest path is of length 5 from node 5 to node 7 This problem is… Read More »

LCA for n-ary Tree | Constant Query O(1)

We have seen various methods with different Time Complexities to calculate LCA in n-ary tree:- Method 1 : Naive Method ( by calculating root to node path) | O(n) per query Method 2 :Using Sqrt Decomposition | O(sqrt H) Method 3 : Using Sparse Matrix DP approach | O(logn) Lets study another method which has… Read More »