LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
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};
  }
};