Category Archives: Trees

Find first non matching leaves in two binary trees

Given two binary trees, find first leaves of two trees that do not match. If there are no non-matching leaves, print nothing. Examples: Input : First Tree 5 / \ 2 7 / \ 10 11 Second Tree 6 / \ 10 15 Output : 11 15 If we consider leaves of two trees in… Read More »

Prufer Code to Tree Creation

What is Prufer Code? Given a tree (represented as graph, not as a rooted tree) with n labeled nodes with labels from 1 to n, a Prufer code uniquely idetifies the tree. The sequence has n-2 values. How to get Prufer Code of a tree? Initialize Prufer code as empty. Start with a leaf of… Read More »

Iterative program to count leaf nodes in a Binary Tree

Given a binary tree, count leaves in the tree without using recursion. A node is a leaf node if both left and right children of it are NULL. Example Tree Leaves count for the above tree is 3. Asked In: GATE-2007 The idea is to use level order traversal. During traversal, if we find a… Read More »

Print all full nodes in a Binary Tree

Given a binary tree, print all nodes will are full nodes. Full Nodes are nodes which has both left and right children as non-empty. Examples: Input : 10 / \ 8 2 / \ / 3 5 7 Output : 10 8 Input : 1 / \ 2 3 / \ 4 6 Output :… Read More »

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 »