树的深度c++
时间: 2023-07-23 13:11:48 浏览: 52
树的深度可以使用深度优先搜索(DFS)或广度优先搜索(BFS)来求解。以下是使用DFS的C++代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
int max_depth = 0;
void dfs(vector<int> adj[], int u, int depth) {
max_depth = max(max_depth, depth);
for(int v : adj[u]) {
dfs(adj, v, depth + 1);
}
}
int main() {
int n, m;
cin >> n >> m;
vector<int> adj[n + 1];
for(int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(adj, 1, 1);
cout << max_depth << endl;
return 0;
}
```
其中,`adj`是邻接表表示的树,`max_depth`表示最大深度,`dfs`是DFS函数,`u`是当前节点,`depth`是当前深度。在`dfs`函数中,遍历当前节点的所有子节点,更新最大深度,并递归遍历子节点。在主函数中,读入树,调用`dfs`函数求解最大深度。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)