Category Archives: Trees

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 »

Print all k-sum paths in a binary tree

A binary tree and a number k are given. Print every path in the tree with sum of the nodes in the path as k. A path can start from any node and end at any node, i.e. they need not be root node and leaf node; and negative numbers can also be there in… Read More »

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 »