-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmaximum-matching.cpp
65 lines (58 loc) · 1.57 KB
/
maximum-matching.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* @file maximum-matching.cpp
* @author prakash ([email protected])
* @brief Maximum matching of a tree in linear time
* @version 0.1
* @date 2021-07-26
*
* @copyright Copyright (c) 2021
*
*/
#include <algorithm>
#include <iostream>
using namespace std;
//Tree node
class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int d) {
data = d;
left = NULL;
right = NULL;
}
};
// maximum matching Bottom-up DFS approach
int max_matching_bottom_up(TreeNode* root) {
if (root == NULL) {
return 0;
}
int matching = 0;
int max_matching = 0;
int left_matching = 0;
int right_matching = 0;
max_matching = max(max_matching, left_matching);
max_matching = max(max_matching, right_matching);
if (root->left != NULL) {
left_matching = max_matching_bottom_up(root->left);
}
if (root->right != NULL) {
right_matching = max_matching_bottom_up(root->right);
}
matching = max(left_matching, right_matching) + 1;
max_matching = max(matching, max_matching);
return max_matching;
}
int main(int argc, const char** argv) {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
root->left->left->left = new TreeNode(8);
cout << "Maximum matching of the tree is " << max_matching_bottom_up(root) << endl;
return 0;
}