当前位置:   article > 正文

2385. 感染二叉树需要的总时间

2385. 感染二叉树需要的总时间

思路:非常巧妙的递归

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. int ans = 0;//答案最小为0
  15. int depth = -1;//start节点深度
  16. int amountOfTime(TreeNode* root, int start) {
  17. dfs(root, 0, start);
  18. return ans;
  19. }
  20. int dfs(TreeNode* root, int level, int start){
  21. if(root == nullptr) return 0;//递归边界
  22. if(root->val == start) depth = level;//保存节点深度
  23. int l = dfs(root->left, level+1, start);//保存左子树深度
  24. bool inle = depth != -1;//判断start节点位置
  25. int r = dfs(root->right, level+1, start);//保存右子树深度
  26. if(root -> val == start) ans = max(ans, max(l, r));//如果从当前节点开始感染,答案就是分钟数
  27. else if(inle) ans = max(ans, depth - level + r);//如果start在左子树,则答案是右子树深度加start深度和根节点深度的差值
  28. else ans = max(ans, depth - level + l);//同理
  29. return max(l, r) + 1;//返回树的深度
  30. }
  31. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/510088
推荐阅读
相关标签
  

闽ICP备14008679号