Given a binary tree of integers, find the maximum path sum between two nodes. The path must go through at least one node and does not need to go through the root.
Example:
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
Approach
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};int sum(TreeNode *root, int &res){if (root == NULL)return 0;//call for left subtreeint left = sum(root->left, res);//call for right subtreeint right = sum(root->right, res);int x = max(max(left, right) + root->data, root->data);int y = max(x, left + right + root->data);res = max(res, y);return x;}int maxPathSum(TreeNode *root){int x = INT_MIN;int res = sum(root, x);return x;}int main(){TreeNode *root = new TreeNode(-10);root->left = new TreeNode(9);root->right = new TreeNode(20);root->right->left = new TreeNode(15);root->right->right = new TreeNode(7);cout << maxPathSum(root);return 0;}
No comments:
Post a Comment