classBinaryTree { public: int value; BinaryTree *left; BinaryTree *right;
BinaryTree(int value); voidinsert(vector<int> values, int i = 0); };
inthelper(BinaryTree tree, int& res){ int path = tree.value; if(tree.left && tree.right) { int l = helper(*tree.left, res); int r = helper(*tree.right, res); res = max({res, path, l + path, r + path, l + r + path}); returnmax({path, l + path, r + path, 0}); } elseif(tree.left) { int l = helper(*tree.left, res); res = max({res, l + path, path}); returnmax({0, path, l + path}); } elseif(tree.right) { int r = helper(*tree.right, res); res = max({res, r + path, path}); returnmax({0, path, r + path}); } else { res = max(res, path); returnmax(0,path); } }
intmaxPathSum(BinaryTree tree){ int res = INT_MIN; helper(tree, res); return res; }