Skip to main content

Command Palette

Search for a command to run...

Binary Trees - Maximum Sum Path Of A Binary Tree

Updated
1 min read
Binary Trees - Maximum Sum Path Of A Binary Tree
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Maximum Sum Path Of A Binary Tree

  1. https://www.codingninjas.com/studio/problems/maximum-sum-path-of-a-binary-tree_1214968

  2. https://leetcode.com/problems/binary-tree-maximum-path-sum/

Hint:

Code:

int helper(BinaryTreeNode<int> *root, int &maxSum){

    if(root==NULL){
        return 0;
    }

    int leftPathSum = helper(root->left, maxSum);
    int rightPathSum = helper(root->right, maxSum);

    int maxi = max(leftPathSum, rightPathSum);

    if(leftPathSum>=0 && rightPathSum>=0){

        maxSum = max(maxSum, leftPathSum+rightPathSum+root->data);
        return root->data+maxi;
    }

    else if(leftPathSum<0 && rightPathSum<0){

        maxSum = max(maxSum, root->data);
        return root->data;
    }

    else{
        maxSum = max(maxSum, maxi+root->data);
        return maxi+root->data;
    }
}

int maxPathSum(BinaryTreeNode<int> *root)
{
    // Write your code here
    int maxSum = -1e9;
    helper(root,maxSum);

    return maxSum;
}

DSA prep

Part 11 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Strings - Implement Atoi Function

Implement Atoi Function Problem Link: https://www.codingninjas.com/studio/problems/implement-atoi-function_981270?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf&leftPanelTabValue=PROBLEM Code: #include<bits/stdc++.h> int createAtoi(s...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.