Skip to content

Latest commit

 

History

History
22 lines (20 loc) · 521 Bytes

File metadata and controls

22 lines (20 loc) · 521 Bytes
  • 存储包含根节点和不包含根节点两种状态能获取的最大收益
class Solution {
 public:
  int rob(TreeNode* root) {
    auto [a, b] = dfs(root);
    return max(a, b);
  }

  pair<int, int> dfs(TreeNode* root) {
    if (!root) {
      return {0, 0};
    }
    auto [l1, l2] = dfs(root->left);
    auto [r1, r2] = dfs(root->right);
    int a = root->val + l2 + r2;  // 包含当前根节点则不包含左右子树的根节点
    int b = max(l1, l2) + max(r1, r2);
    return {a, b};
  }
};