# C Program to Find the Size of Largest Independent Set (LIS) in a Binary Tree

«
»
This is a C Program to find the size of largest independent set in a given binary tree. Given a Binary Tree, find size of the Largest Independent Set(LIS) in it. A subset of all tree nodes is an independent set if there is no edge between any two nodes of the subset.
For example, consider the following binary tree. The largest independent set(LIS) is {10, 40, 60, 70, 80} and size of the LIS is 5.

Here is source code of the C Program to Find Size of the Largest Independent Set(LIS) in a Given a Binary Tree. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `// A naive recursive implementation of Largest Independent Set problem`
2. `#include <stdio.h>`
3. `#include <stdlib.h>`
4. ` `
5. `// A utility function to find max of two integers`
6. `int max(int x, int y) {`
7. `    return (x > y) ? x : y;`
8. `}`
9. ` `
10. `/* A binary tree node has data, pointer to left child and a pointer to`
11. ` right child */`
12. `struct node {`
13. `    int data;`
14. `    struct node *left, *right;`
15. `};`
16. ` `
17. `// The function returns size of the largest independent set in a given`
18. `// binary tree`
19. `int LISS(struct node *root) {`
20. `    if (root == NULL)`
21. `        return 0;`
22. ` `
23. `    // Caculate size excluding the current node`
24. `    int size_excl = LISS(root->left) + LISS(root->right);`
25. ` `
26. `    // Calculate size including the current node`
27. `    int size_incl = 1;`
28. `    if (root->left)`
29. `        size_incl += LISS(root->left->left) + LISS(root->left->right);`
30. `    if (root->right)`
31. `        size_incl += LISS(root->right->left) + LISS(root->right->right);`
32. ` `
33. `    // Return the maximum of two sizes`
34. `    return max(size_incl, size_excl);`
35. `}`
36. ` `
37. `// A utility function to create a node`
38. `struct node* newNode(int data) {`
39. `    struct node* temp = (struct node *) malloc(sizeof(struct node));`
40. `    temp->data = data;`
41. `    temp->left = temp->right = NULL;`
42. `    return temp;`
43. `}`
44. ` `
45. `// Driver program to test above functions`
46. `int main() {`
47. `    // Let us construct the tree given in the above diagram`
48. `    struct node *root = newNode(20);`
49. `    root->left = newNode(8);`
50. `    root->left->left = newNode(4);`
51. `    root->left->right = newNode(12);`
52. `    root->left->right->left = newNode(10);`
53. `    root->left->right->right = newNode(14);`
54. `    root->right = newNode(22);`
55. `    root->right->right = newNode(25);`
56. ` `
57. `    printf("Size of the Largest Independent Set is %d ", LISS(root));`
58. ` `
59. `    return 0;`
60. `}`

Output:

```\$ gcc LargestIndependentSetBinaryTree.c
\$ ./a.out

Size of the Largest Independent Set is 5```

Sanfoundry Global Education & Learning Series – 1000 C Programs. 