剑指 Offer 55 - I. 二叉树的深度
解题思路:递归+回溯
算法流程:
- dfs(TreeNode* root,int tmp)函数递归;
- 终止条件: 若节点 root 为空,则直接返回。
- 递推工作:
1)深度更新:tmp初始值为根节点1,递推tmp+1;
2)先序遍历: 递归左 / 右子节点。
5)集合更新: 向上回溯前,需要将当前节点的深度加入集合res中,即res.insert(tmp); - 调用函数dfs,返回集合res中的最大值,即最后一个值*(res.end()).
class Solution {
public:
int maxDepth(TreeNode* root) {
DFS(root,1);
return *(res.end());
}
public:
set<int> res;
void DFS(TreeNode* root,int tmp)
{
if(root == NULL)
{
return;
}
tmp += 1;
DFS(root->left,tmp);
DFS(root->right,tmp);
res.insert(tmp);
}
};