• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Maximum path sum between two leaves

May 11, 2015 by Dhaval Dave

If a binary tree is given, how to find Maximum path sum between two leaves  of binary tree.

All should be numbers
The maximum sum path may or may not go through root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 – 1 + 10). Expected time complexity is O(n).

Algorithm :

1) We need sum for left and right binary sub tree.
2) we need to maintain current sum including that node ( ex : 2 , -8, 6 )
3) compare current sum with previously obtained result and mark result with respect to it.
4) return maximum of Left or Right subTree + Current Node’s value.
// as we need to get Left / Right subTree sum in recursion.
// till now’s maximum value is getting handled by result.

maximum path sum between two leaves
maximum path sum between two leaves

to understand logic see how Sum for every node

for node = -8 Sum is = 0 , ls = 2 rs = 6
for node = 5 Sum is = 4 , ls = -2 rs = 1
for leaf = -1 Sum is = 4
for node = 0 Sum is = 13 , ls = 4 rs = 9
for leaf = 9 Sum is = 13
for node = 6 Sum is = 27 , ls = 3 rs = 18
for node = -15 Sum is = 27 , ls = 6 rs = 24
Max pathSum of the given binary tree is 27

So Now we can understand that.

1) Recursive call to left and right subtree.
2) to hold current sum.
currentSum = leftSum + rightSum + root->value;
3) To store result we need to pass it with reference, so that in each recursion it stays constant.
4) return Maximum(leftSum, rightSum) + root->value.

int maxPathSumUtil(struct Node *root, int &result) {
    if (root==NULL) return 0;
         //Step1
    int lLPSum = maxPathSumUtil(root->left, result);
    int rLPSum = maxPathSumUtil(root->right, result);
         //Step2
    int curr_sum = lLPSum + rLPSum + root->data;
         
         //Step3
    if (result < curr_sum) result = curr_sum;           
       
         //Step4     
    return max(lLPSum, rLPSum)+root->data;
}
 
int maxPathSum(struct Node *root) {
    int res = 0;
    maxPathSumUtil(root, result);
    cout<< result;
}

Understand how to code in C++

// C++ program to find maximum path sum between two leaves of  Bin Tree by Gohired.in
#include <iostream>
#include <climits>
using namespace std;

struct Node
{
	int data;
	struct Node* left, *right;
};

struct Node* newNode(int data)
{
	struct Node* node = new(struct Node);
	node->data = data;
	node->left = node->right = NULL;
	return (node);
}

int max(int a, int b)
{ return (a >= b)? a: b; }

int maxPathSumUtil(struct Node *root, int &res)
{
	if (root==NULL) return 0;
	if (!root->left && !root->right) return root->data;

	int ls = maxPathSumUtil(root->left, res);
	int rs = maxPathSumUtil(root->right, res);


	if (root->left && root->right)
	{   
	    res = max(res, ls + rs + root->data);
		int temp  =  max(ls, rs) + root->data;
		cout << "for node = " <<root->data << " Sum is = " <<temp <<" ls = "<< ls <<" rs = " << rs <<endl;
		return temp;
	}
    
    int temp = (!root->left)? rs + root->data:ls + root->data; 
	cout << "for leaf = " <<root->data << " Sum is = "<< temp <<endl;
	return temp;
}
int main()
{
    int res = INT_MIN;
	struct Node *root = newNode(-10);
	root->left = newNode(25);
	root->right = newNode(6);
	root->left->left = newNode(-8);
	root->left->right = newNode(1);
	root->left->left->left = newNode(2);
	root->left->left->right = newNode(6);
	root->right->left = newNode(3);
	root->right->right = newNode(9);
	root->right->right->right= newNode(0);
	root->right->right->right->left= newNode(4);
	//root->right->right->right->right= newNode(-1);
	//root->right->right->right->right->left= newNode(10);
	maxPathSumUtil(root,res);
	cout << "Max pathSum of the given binary tree is " <<res;
	return 0;
}

Similar Articles

Filed Under: Amazon Interview Question, Interview Questions, problem Tagged With: Binary Tree, tree

Reader Interactions

Comments

  1. Anonymous says

    May 25, 2015 at 6:32 pm

    The think is right,but the code has some mistakes.
    You can log in leetcode(https://leetcode.com/problems/binary-tree-maximum-path-sum/) to test your code.

    Best wishes!

  2. Hengameh says

    September 20, 2015 at 8:30 am

    In 4th step:
    4) return Maximum(leftSum, rightSum) + root->value.
    what if this one was the max:
    leftSum + rightSum + root->value.

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

Binary Tree Isomorphic to each other

C++ OOPs Part1

Puzzle : 100 doors in a row Visit and Toggle the door. What state the door will be after nth pass ?

Reversal of LinkedList

Given a float number convert it into the string WITHOUT using any inbuilt Function

Reverse a Linked List in groups of given size

Minimum insertions to form a palindrome

Maximum size of square sub matrix with all 1’s in a binary matrix

Printing each word reverse in string

Memory Efficient LinkedList

write a c program that given a set a of n numbers and another number x determines whether or not there exist two elements in s whose sum is exactly x

SAP Off Campus Hiring_ March 2015 Sample Questions

Common Ancestor in a Binary Tree or Binary Search Tree

Test Cases for Round Function

N Petrol bunks or City arranged in circle. You have Fuel and distance between petrol bunks. Is it possible to find starting point so that we can travel all Petrol Bunks

Difference between a LinkedList and a Binary Search Tree BST

Convert Decimal to Roman numbers / Romanizer HackerEarth Code

SAP Interview Questions

Walmart Labs Interview Experience

Code Chef PRGIFT Solution

Find loop in Singly linked list

Implement a generic binary search algorithm for Integer Double String etc

Rectangular chocolate bar Create at least one piece which consists of exactly nTiles tiles

Calculate price of parking from parking start end time prices

Given a sorted array and a number x, find the pair in array whose sum is closest to x

Implement LRU Cache

Maximum sum contiguous subarray of an Array

Leetcode: Merge Intervals

Templates in C++

Sort Stack in place

Copyright © 2025 · Genesis Framework · WordPress · Log in