| 153 | |
| 154 | |
| 155 | fn get_independent_headers(trees: &[TreeNode]) -> Result<Vec<&str>> { |
| 156 | use std::collections::{HashMap, HashSet}; |
| 157 | |
| 158 | // Collect all nodes and their inclusion relationships |
| 159 | let mut all_nodes: HashMap<&str, &TreeNode> = HashMap::new(); |
| 160 | let mut included_by_others: HashSet<&str> = HashSet::new(); |
| 161 | let mut includes_map: HashMap<&str, HashSet<&str>> = HashMap::new(); |
| 162 | |
| 163 | // Recursively collect all nodes and dependency relationships |
| 164 | fn collect_nodes<'a>( |
| 165 | node: &'a TreeNode, |
| 166 | all_nodes: &mut HashMap<&'a str, &'a TreeNode>, |
| 167 | included_by_others: &mut HashSet<&'a str>, |
| 168 | includes_map: &mut HashMap<&'a str, HashSet<&'a str>> |
| 169 | ) { |
| 170 | let name = node.get_name(); |
| 171 | all_nodes.insert(name, node); |
| 172 | |
| 173 | let mut children_set = HashSet::new(); |
| 174 | |
| 175 | // Collect all child nodes, which are included by the current node |
| 176 | for child in &node.children { |
| 177 | let child_name = child.get_name(); |
| 178 | included_by_others.insert(child_name); |
| 179 | children_set.insert(child_name); |
| 180 | collect_nodes(child, all_nodes, included_by_others, includes_map); |
| 181 | } |
| 182 | |
| 183 | includes_map.insert(name, children_set); |
| 184 | } |
| 185 | |
| 186 | // Collect nodes for each tree |
| 187 | for tree in trees { |
| 188 | collect_nodes(tree, &mut all_nodes, &mut included_by_others, &mut includes_map); |
| 189 | } |
| 190 | |
| 191 | // Find all root nodes (nodes not included by any other nodes) |
| 192 | let mut independent_headers: Vec<&str> = Vec::new(); |
| 193 | |
| 194 | for name in all_nodes.keys() { |
| 195 | if !included_by_others.contains(name) { |
| 196 | independent_headers.push(name); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | // If independent headers are found, return them directly |
| 201 | if !independent_headers.is_empty() { |
| 202 | independent_headers.sort(); |
| 203 | independent_headers.dedup(); |
| 204 | return Ok(independent_headers); |
| 205 | } |
| 206 | |
| 207 | // No independent headers found, possible circular dependencies exist |
| 208 | // Use greedy algorithm to find minimum coverage set |
| 209 | let mut result = Vec::new(); |
| 210 | let mut covered: HashSet<&str> = HashSet::new(); |
| 211 | let mut remaining_nodes: HashSet<&str> = all_nodes.keys().cloned().collect(); |
| 212 | |