Javatpoint Logo
Javatpoint Logo

Largest Independent Set in Java

A binary tree is given to us. Our task is to find the size of the largest independent set of the given binary tree. An independent set of a binary tree consists of only those nodes of the binary tree that are not connected directly with each other. In other words, for any two nodes in the set, there has to be at least one node between them.

Example:

Input:

For the following binary tree:

Largest Independent Set in Java

The largest independent set is {100, 400, 600, 700, 800} as these nodes are not adjacent to each other. Its size is 5. Hence, the output is 5.

Approach: Using Recursion

The approach is simple. A node of the given binary tree can be part of the solution or can not be part of the solution. We can have recursive calls based on these two conditions. One recursive call includes the node, and the other excludes the node in the solution. The following implementation shows the same.

FileName: LIS.java

Output:

The size of the Largest Independent Set is: 5

Complexity Analysis: In the above program, each recursive call leads to two recursive (one for excluding, another for including the element in the solution) calls. Therefore, the time complexity of the program is O(2n), where n is the total number of nodes present in the binary tree. Note that it is the exponential time complexity.

The time complexity of the program is very high as it is exponential. Therefore, for handling the larger inputs, the above program is not suitable, and hence it is required to do some optimization.

Approach: Using Recursion With Memoization

The above program is computing many subproblems again and again, and that leads to higher time complexity. For example, A node with the value 500 is computed for the nodes with the values 100 and 200, where the node with the value 500 acts as a grandchild of the node with value 100 and as a child of the node of value 200. Therefore, we need to build the solution in a bottom-up manner and store the solution of the subproblems so that it is not getting computed again and again.

Let's observe the modified form of the above program.

FileName: LIS1.java

Output:

The size of the Largest Independent Set is: 5

Complexity Analysis: Because of the memorization, the time complexity of the program is O(n), where n is the total number of nodes present in the binary tree.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA