From d4daef739b767a49f735c38b3ff24a9c6a97dc17 Mon Sep 17 00:00:00 2001 From: Aakanksha Garg <2024ucs0077@iitjammu.ac.in> Date: Mon, 27 Oct 2025 06:04:58 +0000 Subject: [PATCH] added solution for tree matching --- 9_tree_algorithms/tree_matching.cpp | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 9_tree_algorithms/tree_matching.cpp diff --git a/9_tree_algorithms/tree_matching.cpp b/9_tree_algorithms/tree_matching.cpp new file mode 100644 index 0000000..8e1c50e --- /dev/null +++ b/9_tree_algorithms/tree_matching.cpp @@ -0,0 +1,44 @@ +#include +#include + +using namespace std; + +int n; +vector> adj; +vector matched; +int matching_size = 0; + +void dfs(int u, int p) { + for (int v : adj[u]) { + if (v != p) { + dfs(v, u); + if (!matched[u] && !matched[v]) { + matched[u] = true; + matched[v] = true; + matching_size++; + } + } + } +} + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + cin >> n; + adj.resize(n + 1); + matched.resize(n + 1, false); + + for (int i = 0; i < n - 1; ++i) { + int a, b; + cin >> a >> b; + adj[a].push_back(b); + adj[b].push_back(a); + } + + dfs(1, 0); + + cout << matching_size << "\n"; + + return 0; +} \ No newline at end of file