思路:非常巧妙的递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int ans = 0;//答案最小为0
int depth = -1;//start节点深度
int amountOfTime(TreeNode* root, int start) {
dfs(root, 0, start);
return ans;
}
int dfs(TreeNode* root, int level, int start){
if(root == nullptr) return 0;//递归边界
if(root->val == start) depth = level;//保存节点深度
int l = dfs(root->left, level+1, start);//保存左子树深度
bool inle = depth != -1;//判断start节点位置
int r = dfs(root->right, level+1, start);//保存右子树深度
if(root -> val == start) ans = max(ans, max(l, r));//如果从当前节点开始感染,答案就是分钟数
else if(inle) ans = max(ans, depth - level + r);//如果start在左子树,则答案是右子树深度加start深度和根节点深度的差值
else ans = max(ans, depth - level + l);//同理
return max(l, r) + 1;//返回树的深度
}
};