classSolution { public: staticconstexprint inf = 0x3f3f3f3f; int res; structSubTree { bool isBST; int minValue; int maxValue; int sumValue; SubTree(bool isBST, int minValue, int maxValue, int sumValue) : isBST(isBST), minValue(minValue), maxValue(maxValue), sumValue(sumValue) {} };
SubTree dfs(TreeNode* root){ if (root == nullptr) { returnSubTree(true, inf, -inf, 0); } auto left = dfs(root->left); auto right = dfs(root->right);
if (left.isBST && right.isBST && root->val > left.maxValue && root->val < right.minValue) { int sum = root->val + left.sumValue + right.sumValue; res = max(res, sum); returnSubTree(true, min(left.minValue, root->val), max(root->val, right.maxValue), sum); } else { returnSubTree(false, 0, 0, 0); } }
intmaxSumBST(TreeNode* root){ res = 0; dfs(root); return res; } };