int left = max(dfs(root->left), 0); int right = max(dfs(root->right), 0); ans = max(ans, left + right + root->val); return max(left, right) + root->val;
classSolution { public: int ans = -1e9; intdfs(TreeNode* root) { if(root == nullptr) return0; int all = -1e9; int left = dfs(root->left) + root->val; int right = dfs(root->right) + root->val; all = left + right - root->val; ans = max(ans, root->val); ans = max(ans, all); ans = max(ans, max(left, right)); return max(root->val, max(left, right)); } intmaxPathSum(TreeNode* root){ dfs(root); return ans; } };