-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLargestIndependentSetProblemTrees.cpp
50 lines (36 loc) · 1.06 KB
/
LargestIndependentSetProblemTrees.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node*left;
Node*right;
Node(int d):data(d),left(NULL),right(NULL){}
};
//return the largest independent set(unconnected nodes) in the binary tree.
int LISS(Node*root){
if(root==NULL){
return 0;
}
int including_current = 1;
if(root->left){
including_current += LISS(root->left->left) + LISS(root->left->right);
}
if(root->right){
including_current += LISS(root->right->left) + LISS(root->right->right);
}
int excluding_current = LISS(root->left) + LISS(root->right);
return max(including_current,excluding_current);
}
int main(){
Node *root = new Node(20);
root->left = new Node(8);
root->left->left = new Node(4);
root->left->right = new Node(12);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
root->right = new Node(22);
root->right->right = new Node(25);
cout<<LISS(root);
return 0;
}