当前位置:   article > 正文

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

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

题目:

题解:

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

闽ICP备14008679号