The Wayback Machine - https://web.archive.org/web/20241009193804/https://www.geeksforgeeks.org/find-maximum-path-sum-two-leaves-binary-tree/
Open In App

Find the maximum path sum between two leaves of a binary tree

Last Updated : 08 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
42.92%
74.1K

Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another. 

The maximum sum path may or may not go through the 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). If one side of the root is empty, then the function should return minus infinite (INT_MIN in case of C/C++)

tree 

A simple solution is to traverse the tree and do following for every traversed node X. 

  1. Find maximum sum from leaf to root in left subtree of X (we can use this post for this and next steps) 
  2. Find maximum sum from leaf to root in right subtree of X. 
  3. Add the above two calculated values and X->data and compare the sum with the maximum value obtained so far and update the maximum value. 
  4. Return the maximum value.

The time complexity of above solution is O(n2)

We can find the maximum sum using single traversal of binary tree. The idea is to maintain two values in recursive calls

(Note: If the tree is right-most or left-most tree then first we have to adjust the tree such that both the right and left are not null. Left-most means if the right of super root of the tree is null and right-most tree means if left of  super root of the tree is null.) 

  1. Maximum root to leaf path sum for the subtree rooted under current node. 
  2. The maximum path sum between leaves (desired output).

For every visited node X, we find the maximum root to leaf sum in left and right subtrees of X. We add the two values with X->data, and compare the sum with maximum path sum found so far.

Following is the implementation of the above O(n) solution.

C++




// C++ program to find maximum path
//sum between two leaves of  a binary tree
#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node
struct Node
{
    int data;
    struct Node* left, *right;
};
 
// Utility function to allocate memory for a new node
struct Node* newNode(int data)
{
    struct Node* node = new(struct Node);
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
// Utility function to find maximum of two integers
int max(int a, int b)
{ return (a >= b)? a: b; }
 
// A utility function to find the maximum sum between any
// two leaves.This function calculates two values:
// 1) Maximum path sum between two leaves which is stored
//    in res.
// 2) The maximum root to leaf path sum which is returned.
// If one side of root is empty, then it returns INT_MIN
int maxPathSumUtil(struct Node *root, int &res;)
{
    // Base cases
    if (root==NULL) return 0;
    if (!root->left && !root->right) return root->data;
 
    // Find maximum sum in left and right subtree. Also
    // find maximum root to leaf sums in left and right
    // subtrees and store them in ls and rs
    int ls = maxPathSumUtil(root->left, res);
    int rs = maxPathSumUtil(root->right, res);
 
 
    // If both left and right children exist
    if (root->left && root->right)
    {
        // Update result if needed
        res = max(res, ls + rs + root->data);
 
        // Return maximum possible value for root being
        // on one side
        return max(ls, rs) + root->data;
    }
 
    // If any of the two children is empty, return
    // root sum for root being on one side
    return (!root->left)? rs + root->data:
                          ls + root->data;
}
 
// The main function which returns sum of the maximum
// sum path between two leaves. This function mainly
// uses maxPathSumUtil()
int maxPathSum(struct Node *root)
{
    int res = INT_MIN;
   
    int val = maxPathSumUtil(root, res);
           
      //--- for test case ---
       //         7                
      //        /    \              
        //    Null   -3           
      //     (case - 1)        
      //   value of res will be INT_MIN but the answer is 4 , which is returned by the
      // function maxPathSumUtil().
   
      if(root->left && root->right)
            return res;
        return max(res, val);
}
 
// Driver Code
int main()
{
    struct Node *root = newNode(-15);
    root->left = newNode(5);
    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);
    cout << "Max pathSum of the given binary tree is "
         << maxPathSum(root);
    return 0;
}


Java




// Java program to find maximum path sum between two leaves
// of a binary tree
class Node {
    int data;
    Node left, right;
 
    Node(int item) {
        data = item;
        left = right = null;
    }
}
 
// An object of Res is passed around so that the
// same value can be used by multiple recursive calls.
class Res {
    int val;
}
 
class BinaryTree {
    static Node root;
 
    // A utility function to find the maximum sum between any
    // two leaves.This function calculates two values:
    // 1) Maximum path sum between two leaves which is stored
    // in res.
    // 2) The maximum root to leaf path sum which is returned.
    int maxPathSumUtil(Node node, Res res) {
 
        // Base cases
        if (node == null)
            return 0;
        if (node.left == null && node.right == null)
            return node.data;
 
        // Find maximum sum in left and right subtree. Also
        // find maximum root to leaf sums in left and right
        // subtrees and store them in ls and rs
        int ls = maxPathSumUtil(node.left, res);
        int rs = maxPathSumUtil(node.right, res);
 
        // If both left and right children exist
        if (node.left != null && node.right != null) {
 
            // Update result if needed
            res.val = Math.max(res.val, ls + rs + node.data);
 
            // Return maximum possible value for root being
            // on one side
            return Math.max(ls, rs) + node.data;
        }
 
        // If any of the two children is empty, return
        // root sum for root being on one side
        return (node.left == null) ? rs + node.data : ls + node.data;
    }
 
    // The main function which returns sum of the maximum
    // sum path between two leaves. This function mainly
    // uses maxPathSumUtil()
    int maxPathSum() {
        Res res = new Res();
        res.val = Integer.MIN_VALUE;
 
        int val = maxPathSumUtil(root, res);
       
        if (root.left != null && root.right != null)
            return res.val;
        else {
               //--- for test case ---
               //         7                
              //        /    \              
                //    Null   -3                   
              // value of res will be INT_MIN but the answer is 4,
              // which is returned by the function maxPathSumUtil()
              return Math.max(res.val,val);
        }
    }
 
    //Driver program to test above functions
    public static void main(String args[]) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(-15);
        tree.root.left = new Node(5);
        tree.root.right = new Node(6);
        tree.root.left.left = new Node(-8);
        tree.root.left.right = new Node(1);
        tree.root.left.left.left = new Node(2);
        tree.root.left.left.right = new Node(6);
        tree.root.right.left = new Node(3);
        tree.root.right.right = new Node(9);
        tree.root.right.right.right = new Node(0);
        tree.root.right.right.right.left = new Node(4);
        tree.root.right.right.right.right = new Node(-1);
        tree.root.right.right.right.right.left = new Node(10);
     
        System.out.println("Max pathSum of the given binary tree is "
                + tree.maxPathSum());
    }
}
 
// This code is improved by Fabio Missagia


Python3




# Python program to find maximumpath sum between two leaves
# of a binary tree
 
INT_MIN = -2**32
 
# A binary tree node
 
 
class Node:
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Utility function to find maximum sum between any
# two leaves. This function calculates two values:
# 1) Maximum path sum between two leaves which are stored
#    in res
# 2) The maximum root to leaf path sum which is returned
# If one side of root is empty, then it returns INT_MIN
 
 
def maxPathSumUtil(root, res):
 
    # Base Case
    if root is None:
        return 0
 
    # if root is leaf node we can return root.data
    if not root.left and not root.right:
        return root.data
 
    # Find maximumsum in left and right subtree. Also
    # find maximum root to leaf sums in left and right
    # subtrees ans store them in ls and rs
    ls = maxPathSumUtil(root.left, res)
    rs = maxPathSumUtil(root.right, res)
 
    # If both left and right children exist
    if root.left is not None and root.right is not None:
 
        # update result if needed
        res[0] = max(res[0], ls + rs + root.data)
 
        # Return maximum possible value for root being
        # on one side
        return max(ls, rs) + root.data
 
    # If any of the two children is empty, return
    # root sum for root being on one side
    if root.left is None:
        return rs + root.data
    else:
        return ls + root.data
 
# The main function which returns sum of the maximum
# sum path betwee ntwo leaves. THis function mainly
# uses maxPathSumUtil()
 
 
def maxPathSum(root):
    res = [INT_MIN]
    res1 = maxPathSumUtil(root, res)
    # we have to check if root.left is None or root.right is None
    # for ex:-   10
    #            /  \
    #         None  -5
    # this will return INT_MIN but answer is 5 which is res1
    if root.left and root.right:
        return res[0]
    return max(res[0], res1)
 
 
# Driver program to test above function
root = Node(-15)
root.left = Node(5)
root.right = Node(6)
root.left.left = Node(-8)
root.left.right = Node(1)
root.left.left.left = Node(2)
root.left.left.right = Node(6)
root.right.left = Node(3)
root.right.right = Node(9)
root.right.right.right = Node(0)
root.right.right.right.left = Node(4)
root.right.right.right.right = Node(-1)
root.right.right.right.right.left = Node(10)
 
print("Max pathSum of the given binary tree is", maxPathSum(root))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




using System;
 
// C# program to find maximum path sum between two leaves
// of a binary tree
public class Node
{
 
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
// An object of Res is passed around so that the
// same value can be used by multiple recursive calls.
public class Res
{
    public int val;
}
 
public class BinaryTree
{
 
    public static Node root;
 
    // A utility function to find the maximum sum between any
    // two leaves.This function calculates two values:
    // 1) Maximum path sum between two leaves which is stored
    //    in res.
    // 2) The maximum root to leaf path sum which is returned.
    // If one side of root is empty, then it returns INT_MIN
    public virtual int maxPathSumUtil(Node node, Res res)
    {
 
        // Base cases
        if (node == null)
        {
            return 0;
        }
        if (node.left == null && node.right == null)
        {
            return node.data;
        }
 
        // Find maximum sum in left and right subtree. Also
        // find maximum root to leaf sums in left and right
        // subtrees and store them in ls and rs
        int ls = maxPathSumUtil(node.left, res);
        int rs = maxPathSumUtil(node.right, res);
 
        // If both left and right children exist
        if (node.left != null && node.right != null)
        {
 
            // Update result if needed
            res.val = Math.Max(res.val, ls + rs + node.data);
 
            // Return maximum possible value for root being
            // on one side
            return Math.Max(ls, rs) + node.data;
        }
 
        // If any of the two children is empty, return
        // root sum for root being on one side
        return (node.left == null) ? rs + node.data : ls + node.data;
    }
 
    // The main function which returns sum of the maximum
    // sum path between two leaves. This function mainly
    // uses maxPathSumUtil()
    public virtual int maxPathSum(Node node)
    {
        Res res = new Res();
        res.val = int.MinValue;
        maxPathSumUtil(root, res);
        return res.val;
    }
 
    //Driver program to test above functions
    public static void Main(string[] args)
    {
        BinaryTree tree = new BinaryTree();
        BinaryTree.root = new Node(-15);
        BinaryTree.root.left = new Node(5);
        BinaryTree.root.right = new Node(6);
        BinaryTree.root.left.left = new Node(-8);
        BinaryTree.root.left.right = new Node(1);
        BinaryTree.root.left.left.left = new Node(2);
        BinaryTree.root.left.left.right = new Node(6);
        BinaryTree.root.right.left = new Node(3);
        BinaryTree.root.right.right = new Node(9);
        BinaryTree.root.right.right.right = new Node(0);
        BinaryTree.root.right.right.right.left = new Node(4);
        BinaryTree.root.right.right.right.right = new Node(-1);
        BinaryTree.root.right.right.right.right.left = new Node(10);
        Console.WriteLine("Max pathSum of the given binary tree is " + tree.maxPathSum(root));
    }
}
 
  // This code is contributed by Shrikant13


Javascript




<script>
// javascript program to find maximum path sum between two leaves
// of a binary tree
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}
 
 
// An object of Res is passed around so that the
// same value can be used by multiple recursive calls.
class Res {
    constructor(){
    this.val = 0;
    }
}
 
var root;
 
function setTree(root) {
 
var temp = new Node(0);
        // if tree is left most
        if (root.right == null) {
            root.right = temp;
        } else { // if tree is right most
            root.left = temp;
        }
 
        return root;
     
    }
 
    // A utility function to find the maximum sum between any
    // two leaves.This function calculates two values:
    // 1) Maximum path sum between two leaves which is stored
    // in res.
    // 2) The maximum root to leaf path sum which is returned.
    // If one side of root is empty, then it returns INT_MIN
    function maxPathSumUtil(node, res) {
 
        // Base cases
        if (node == null)
            return 0;
        if (node.left == null && node.right == null)
            return node.data;
 
        // Find maximum sum in left and right subtree. Also
        // find maximum root to leaf sums in left and right
        // subtrees and store them in ls and rs
        var ls = maxPathSumUtil(node.left, res);
        var rs = maxPathSumUtil(node.right, res);
 
        // If both left and right children exist
        if (node.left != null && node.right != null) {
 
            // Update result if needed
            res.val = Math.max(res.val, ls + rs + node.data);
 
            // Return maximum possible value for root being
            // on one side
            return Math.max(ls, rs) + node.data;
        }
 
        // If any of the two children is empty, return
        // root sum for root being on one side
        return (node.left == null) ? rs + node.data : ls + node.data;
    }
 
    // The main function which returns sum of the maximum
    // sum path between two leaves. This function mainly
    // uses maxPathSumUtil()
    function maxPathSum(node) {
        var res = new Res();
        res.val = Number.MIN_VALUE;
 
        if (root.left == null || root.right == null) {
            root = setTree(root);
        }
         
        // if tree is left most or right most
        // call setTree() method to adjust tree first
        maxPathSumUtil(root, res);
        return res.val;
    }
 
    // Driver program to test above functions
        var root = new Node(-15);
        root.left = new Node(5);
        root.right = new Node(6);
        root.left.left = new Node(-8);
        root.left.right = new Node(1);
        root.left.left.left = new Node(2);
        root.left.left.right = new Node(6);
        root.right.left = new Node(3);
        root.right.right = new Node(9);
        root.right.right.right = new Node(0);
        root.right.right.right.left = new Node(4);
        root.right.right.right.right = new Node(-1);
        root.right.right.right.right.left = new Node(10);
        document.write("Max pathSum of the given binary tree is " + maxPathSum(root));
 
// This code is contributed by umadevi9616
</script>


Output

Max pathSum of the given binary tree is 27

Time complexity: O(n) where n is the number of nodes
Auxiliary Space: O(n)



Similar Reads

Minimum sum path between two leaves of a binary tree
Given a binary tree in which each node element contains a number. The task is to find the minimum possible sum from one leaf node to another.If one side of root is empty, then function should return minus infinite.Examples: Input : 4 / \ 5 -6 / \ / \ 2 -3 1 8 Output : 1 The minimum sum path between two leaf nodes is: -3 -> 5 -> 4 -> -6 -
10 min read
Tree with N nodes and K leaves such that distance between farthest leaves is minimized
Given N and K, print a tree such that the tree has no more than K leaf nodes and every other node has at least two nodes connected to it. The task is to build a tree of N nodes exactly in such a way that the distance between the farthest leaf nodes is minimized. Print the minimized distance also. Note: There can be multiple trees. Examples: Input:
6 min read
Find sum of all left leaves in a given Binary Tree
Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6. Recommended PracticeSum of Left Leaf NodesTry It! The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then add it to the result. Following is the implementati
15+ min read
Find sum of all right leaves in a given Binary Tree
Given a Binary Tree, find sum of all right leaves in it. Similar article: Find sum of all left leaves in a given Binary Tree Example : Input : 1 / \ 2 3 / \ \ 4 5 8 \ / \ 2 6 7 Output : sum = 2 + 5 + 7 = 14Recommended PracticePaths from root with a specified sumTry It! Method 1: Recursive Method The idea is to traverse the tree starting from the ro
15+ min read
Find first non matching leaves in two binary trees
Given two binary trees, find the first leaves of two trees that do not match. If there are no non-matching leaves, print nothing. Examples: Input : First Tree 5 / \ 2 7 / \ 10 11 Second Tree 6 / \ 10 15 Output : 11 15 If we consider leaves of two trees in order, we can see that 11 and 15 are the first leaves that do not match. Method 1 (Simple) : D
14 min read
Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea i
15 min read
Height of binary tree considering even level leaves only
Find the height of the binary tree given that only the nodes on the even levels are considered valid leaf nodes. The height of a binary tree is the number of edges between the tree's root and its furthest leaf. But what if we bring a twist and change the definition of a leaf node? Let us define a valid leaf node as the node that has no children and
8 min read
Lowest Common Ancestor of the deepest leaves of a Binary Tree
Given a Binary Tree consisting of N nodes having distinct values from the range [1, N], the task is to find the lowest common ancestor of the deepest leaves of the binary tree. Examples: Input: Output: 1Explanation: The deepest leaf nodes of the tree are {8, 9, 10}. Lowest common ancestor of these nodes is 1. Input: Output: 6 Approach: The given pr
10 min read
Extract Leaves of a Binary Tree in a Doubly Linked List
Given a Binary Tree, extract all leaves of it in a Doubly Linked List (DLL). Note that the DLL need to be created in-place. Assume that the node structure of DLL and Binary Tree is same, only the meaning of left and right pointers are different. In DLL, left means previous pointer, and right means next pointer. Let the following be input binary tre
11 min read
Print all nodes in a binary tree having K leaves
Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples : // For above binary tree Input : k = 2 Output: {3} // here node 3 have k = 2 leaves Input : k = 1 Output: {6} // here node 6 have k = 1 leaveRecommended PracticePrint Nodes having K leavesTry It! Here
7 min read
Find the maximum sum leaf to root path in a Binary Tree
Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root. Example : Input: Output: 60Explanantion: There are three leaf to root paths 20->30->10, 5->30->10 and 15->10. The sums of these three paths are 60, 45 and 25 respectively. The maximum of them is 60 and the path for maximum is 20->30->10. Table
15+ min read
Maximum Path Sum in a Binary Tree
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. Example: Input: Root of below tree 1 / \ 2 3 Output: 6 Input: Output: 42Explanation: Max path sum is represented using green color nodes in the above binary tree Recommended PracticeMaximum path sum from any nodeTry It!Approach: To solve the problem
15+ min read
Check if max sum level of Binary tree divides tree into two equal sum halves
Given a Binary Tree, the task is to check if the maximum sum level divides the binary tree into the two parts of two equal sum halves.Examples: Input: 1 / \ 2 3 / \ \ 4 5 8 / \ 2 4 Output: YES Explanation: The maximum sum level is 2 and its sum is (4 + 5 + 8 = 17) Sum of the upper half (1 + 2 + 3) = 6 Sum of the Lower half (2 + 4) = 6 Input: 10 / \
11 min read
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
XOR of path between any two nodes in a Binary Tree
Given a binary tree with distinct nodes and a pair of two nodes. The task is to find the XOR of all of the nodes which comes on the path between the given two nodes. For Example, in the above binary tree for nodes (3, 5) XOR of path will be (3 XOR 1 XOR 0 XOR 2 XOR 5) = 5. The idea is to make use of these two properties of XOR: XOR of same elements
8 min read
Print path between any two nodes in a Binary Tree
Given a Binary Tree of distinct nodes and a pair of nodes. The task is to find and print the path between the two given nodes in the binary tree. For Example, in the above binary tree the path between the nodes 7 and 4 is 7 -> 3 -> 1 -> 4. The idea is to find paths from root nodes to the two nodes and store them in two separate vectors or
12 min read
Print path between any two nodes in a Binary Tree | Set 2
Given a Binary Tree of distinct nodes and a pair of nodes. The task is to find and print the path between the two given nodes in the binary tree.Examples: Input: N1 = 7, N2 = 4 Output: 7 3 1 4 Approach: An approach to solve this problem has been discussed in this article. In this article, an even optimized recursive approach will be discussed. In t
15 min read
Shortest path between two nodes in array like representation of binary tree
Consider a binary tree in which each node has two children except the leaf nodes. If a node is labeled as 'v' then its right children will be labeled as 2v+1 and left children as 2v. Root is labelled asGiven two nodes labeled as i and j, the task is to find the shortest distance and the path from i to j. And print the path of node i and node j from
12 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Minimum number of leaves required to be removed from a Tree to satisfy the given condition
Given a Tree consisting of N vertices, rooted at vertex 1 and an array val[] representing the values assigned to each vertex, and an array cost[] representing the cost of each edge in the Tree, the task is to find the minimum number of leaves to be removed from the given tree such that: For any vertex V, the sum of cost of edges to a vertex U in it
8 min read
All Leaves of a Bnary Tree - Print in Order
Given a binary tree, we need to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.  For Example,  Input : Root of the below tree Output : 4 6 7 9 10 Corner Cases : For a tree with single node, the output should be the single node. And
11 min read
Maximum absolute difference between any two level sum in a Binary Tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum absolute difference of level sum in it. Examples: Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 9 Explanation: Sum of all nodes of 0 level is 4 Sum of all nodes of 1 level is -3 Sum of all nodes of 2 level is 6 Hence maximum absolute difference of level sum = 9 (6
10 min read
Find all root to leaf path sum of a Binary Tree
Given a Binary Tree, the task is to print all the root to leaf path sum of the given Binary Tree. Examples: Input: 30 / \ 10 50 / \ / \ 3 16 40 60 Output: 43 56 120 140 Explanation: In the above binary tree there are 4 leaf nodes. Hence, total 4 path sum are present from root node to the leaf node. (i.e., 30-10-3, 30-10-16, 30-50-40, 30-50-60) Ther
8 min read
Minimum count of Full Binary Trees such that the count of leaves is N
Given an integer N and an infinite number of Full Binary Trees of different depths, the task is to choose minimum number of trees such that the sum of the count of leaf nodes in each of the tree is N.Example: Input: N = 7 Output: 3 Trees with depths 2, 1 and 0 can be picked with the number of leaf nodes as 4, 2 and 1 respectively. (4 + 2 + 1) = 7In
3 min read
Find path between lowest and highest value in a Binary tree
Given a binary tree consisting of N nodes. Find the path between the node having the lowest value to the node having the highest value. There is no restriction on the traversal, i.e. the tree can be traversed upward, bottom, left and right. Examples: Input: N = 8 2 / \ 1 6 / \ \ 4 21 26 / \5 7 {(2), (1, 6), (4, 21), (26), (5), (7)}Output: 1 -> 2
10 min read
Minimum cost such that path sum is at max K (Target Path Sum)
Given a rooted tree consisting of N vertices. The vertices are numbered from 0 to N-1, and the root is the vertex 0. You are also given a value array Arr: Arr0, Arr1,....., Arrn-1. You can do any of these moves any number of times: Pick any node that is not root cut the edge between it and its parent and connect an edge between this node to the roo
11 min read
Find maximum path sum in a 2D matrix when exactly two left moves are allowed
Given a 2D matrix arr[][] of dimensions N * M where N is number of rows and M is number of columns.The task is to find maximum path sum in this matrix satisfying some condition which are as follows : We can only start with arr[i][M] where 0 <= i <= N.We end the path on the same side, such that we can take exactly 2 left turns.First we calcula
2 min read
Construct a Maximum Binary Tree from two given Binary Trees
Given two Binary Trees, the task is to create a Maximum Binary Tree from the two given binary trees and print the Inorder Traversal of that tree. What is the maximum Binary Tree? The maximum binary is constructed in the following manner: In the case of both the Binary Trees having two corresponding nodes, the maximum of the two values is considered
8 min read
Maximum XOR path of a Binary Tree
Given a Binary Tree, the task is to find the maximum of all the XOR value of all the nodes in the path from the root to leaf.Examples: Input: 2 / \ 1 4 / \ 10 8 Output: 11 Explanation: All the paths are: 2-1-10 XOR-VALUE = 9 2-1-8 XOR-VALUE = 11 2-4 XOR-VALUE = 6 Input: 2 / \ 1 4 / \ / \ 10 8 5 10 Output: 12 Approach: To solve the question mentione
8 min read
Maximum product of any path in given Binary Tree
Given a binary tree of N nodes, the task is to find the maximum product of the elements of any path in the binary tree. Note: A path starts from the root and ends at any leaf in the tree. Examples: Input: 4 / \ 2 8 / \ / \2 1 3 4 Output: 128Explanation: Path in the given tree goes like {4, 8, 4} which gives the max score of 4 x 8 x 4 = 128. Input:
5 min read