Given a binary tree, find the size of the Maximum Independent Set (MIS) in it.

An independent set is a set of nodes in a binary tree, no two of which are adjacent, i.e., there is no edge connecting any two. The size of an independent set is the total number of nodes it contains. The maximum independent set problem is finding an independent set of the largest possible size for a given binary tree.

For example, the Maximum Independent Set (MIS) of the following binary tree is [1, 4, 6, 7, 8].

Maximum Independent Set Problem

Practice this problem

From the above example, it is evident that if a node is considered part of MIS, its left and right child cannot be part of MIS. However, its grandchildren can be part of MIS.

 
The idea is to traverse the binary tree, and for each node in the binary tree, there are two possible cases:

  1. Exclude the current node from the maximum independent set and process its children.
  2. Include the current node in the maximum independent set and process its grandchildren.

Accordingly, return the maximum number of nodes possible by either including or excluding the current node. The algorithm can be implemented recursively as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The size of a maximum independent set is 5

Java


Download  Run Code

Output:

The size of a maximum independent set is 5

Python


Download  Run Code

Output:

The size of a maximum independent set is 5

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).

 
It can be seen that the problem has an optimal substructure since it can be broken down into smaller subproblems, which can further be broken down into yet smaller subproblems, and so on. The problem also exhibits overlapping subproblems, so we will end up solving the same subproblem over and over again.

We know that problems having optimal substructure and overlapping subproblems can be solved by dynamic programming, in which subproblem solutions are memoized to avoid recomputation of the same subproblems. The dynamic programming solution can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The size of a maximum independent set is 5

Java


Download  Run Code

Output:

The size of a maximum independent set is 5

Python


Download  Run Code

Output:

The size of a maximum independent set is 5

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the total number of nodes in the binary tree.