当前位置:   article > 正文

C++ | Leetcode C++题解之第337题打家劫舍III

C++ | Leetcode C++题解之第337题打家劫舍III

题目:

题解:

  1. struct SubtreeStatus {
  2. int selected;
  3. int notSelected;
  4. };
  5. class Solution {
  6. public:
  7. SubtreeStatus dfs(TreeNode* node) {
  8. if (!node) {
  9. return {0, 0};
  10. }
  11. auto l = dfs(node->left);
  12. auto r = dfs(node->right);
  13. int selected = node->val + l.notSelected + r.notSelected;
  14. int notSelected = max(l.selected, l.notSelected) + max(r.selected, r.notSelected);
  15. return {selected, notSelected};
  16. }
  17. int rob(TreeNode* root) {
  18. auto rootStatus = dfs(root);
  19. return max(rootStatus.selected, rootStatus.notSelected);
  20. }
  21. };
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/999707
推荐阅读
相关标签
  

闽ICP备14008679号