Category Archives: Trees

Convert a tree to forest of even nodes

Given a tree of n even nodes. The task is to find the maximum number of edges to be removed from the given tree to obtain forest of trees having even number of nodes. This problem is always solvable as given graph has even nodes. Examples: Input : n = 10 Edge 1: 1 3… Read More »

Diameter of an N-ary tree

The diameter of an N-ary tree is the longest path present between any two nodes of the tree. These two nodes must be two leaf nodes. The following examples have the longest path[diameter] shaded. Examples: Example 2: Prerequisite : Diameter of a binary tree. The path can either start from one of the node and… Read More »

Depth of an N-Ary tree

Given an N-Ary tree, find depth of the tree. An N-Ary tree is a tree in which nodes can have at most N children. Examples: Example 1: Example 2: N-Ary tree can be traversed just like a normal tree. We just have to consider all childs of a given node and recursively call that function… Read More »

Calculate depth of a full Binary tree from Preorder

Given preorder of a binary tree, calculate its depth(or height) [starting from depth 0]. The preorder is given as a string with two possible characters. ‘l’ denotes the leaf ‘n’ denotes internal node The given tree can be seen as a full binary tree where every node has 0 or two children. The two children… Read More »

Subtree with given sum in a Binary Tree

You are given a binary tree and a given sum. The task is to check if there exist a subtree whose sum of all nodes is equal to the given sum. Examples: // For above tree Input : sum = 22 Output: “Yes” // sum of all nodes of subtree {1, 7, 12, 2} =… Read More »

Print all nodes in a binary tree having K leaves

Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples: // For above binary tree Input : k = 2 Output: {5, 7} // here node 5 and 7 have k = 2 leaves Input :… Read More »