递归算法精讲:牛客13279题树的高度计算 | DFS实战教程
一、问题理解与算法思路
牛客13279题要求计算给定树结构的高度(深度)。树的高度定义为从根节点到最远叶子节点的最长路径上的节点数。本文通过递归深度优先搜索(DFS)的方法,提供了一种简洁高效的解决方案。
二、完整代码实现(带详细注释)
#include <iostream> #include <vector> #include <algorithm> using namespace std; int computeHeight(const vector<vector<int>>& tree, int node) { int maxHeight = 0; for (int child : tree[node]) { maxHeight = max(maxHeight, computeHeight(tree, child)); } return maxHeight + 1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<vector<int>> tree(n); // 邻接表存储树结构 for (int i = 0; i < n - 1; ++i) { int parent, child; cin >> parent >> child; tree[parent].push_back(child); } cout << computeHeight(tree, 0) << endl; return 0; }
三、关键算法解析
递归思想:采用分治策略,将大树分解为子树处理
邻接表存储:使用vector<vector>高效表示树结构
基准情况:当节点无子节点时,递归自然终止
递归关系:节点高度 = 所有子树最大高度 + 1
四、复杂度分析
时间复杂度:O(n) - 每个节点恰好访问一次
空间复杂度:O(h) - 递归栈空间,h为树高
五、常见错误提醒
忘记处理空树的情况
递归终止条件不正确
输入数据格式处理错误
邻接表构建错误
参考:牛客13279题解
原创内容 转载请注明出处