Find the maximum path sum between two nodes

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 treenode
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
int sum(TreeNode *rootint &res)
{
    if (root == NULL)
        return 0;

    //call for left subtree
    int left = sum(root->leftres);

    //call for right subtree
    int right = sum(root->rightres);

    int x = max(max(leftright) + root->dataroot->data);
    int y = max(xleft + right + root->data);
    res = max(resy);
    return x;
}
int maxPathSum(TreeNode *root)
{
    int x = INT_MIN;
    int res = sum(rootx);
    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