This question looks like a recursive algorithm. For a tree, there are three situations: Root, left subtree, right subtree, and Recursive Maximum value, in the first case (the path contains the root), we can see that it will always contain the root, and the last two are complex points. We need to recursively process each subtree. The Code is as follows:
int maxPathSumWithRoot(TreeNode *root) {if (root == nullptr) return 0;int left = maxPathSumWithRoot(root->left);int right = maxPathSumWithRoot(root->right);return max(0, max(left + root->val, right + root->val));}int maxPathSum(TreeNode *root){if (root == nullptr) return 0;int maxWithR = maxPathSumWithRoot(root);int lmax = maxPathSum(root->left);int rmax = maxPathSum(root->right);return max(maxWithR, max(lmax, rmax));}
After submitting the application, I found that the recursion in maxpathsum is unreasonable because it contains another recursive program, and it becomes an O (N ^ 2). In fact, the three situations I considered in the above program are repeated. Simply put, when a parent node contains only the left subtree, the root is included in the left subtree (or a subtree of the parent node). The right subtree is the same, so recursively speaking, there is only one situation. what is different is the root node. If I haven't written it clearly, I can try to understand this. Whatever the path, it always belongs to a subtree. That is to say, there will always be a node in the path as the root node.
What is hard to come up with here is to use a global variable to record the results in the traversal process (the so-called global variable only needs to be changed in every recursion, so it is implemented by reference passing parameters ), the return value is the maximum path and value obtained from the root node of the current node.
int helper(TreeNode *root, int &result){if (root == nullptr) return 0;int left = helper(root->left, result);int right = helper(root->right, result);int cur = root->val + max(left, 0) + max(right, 0);if (cur > result)result = cur;return root->val + max(left, max(right, 0));}int maxPathSum(TreeNode *root){if (root == nullptr)return 0;int result = INT_MIN;helper(root, result);return result;}
Binary Tree maximum path sum