Maximum sum leaf to root path

Last Updated : 26 May, 2026

Given root of a Binary tree, find the maximum sum path from any leaf node to the root.

Example :

Input: root[] = [1, 2, 3, 4, 5, N, 8, N, 2, N, N, 6, 7]

blobid3_1779520846

Output: 19
Explanation: There are 4 leaf nodes in the tree, resulting in 4 leaf-to-root paths:
2 -> 4 -> 2 -> 1, 5 -> 2 -> 1, 6 -> 8 -> 3 -> 1, and 7 -> 8 -> 3 -> 1.
Among these, the path 7 -> 8 -> 3 -> 1 has the maximum sum.
The sum of this path is 7 + 8 + 3 + 1 = 19.

Input: root[] = [1, -2, 3, N, 5, N, 8]     

blobid4_1779527134

Output: 12
Explanation: There are 2 leaf nodes in the tree, resulting in 2 leaf-to-root paths:
5 -> -2 -> 1 and 8 -> 3 -> 1.
Among these, the path 8 -> 3 -> 1 has the maximum sum.
The sum of this path is 8 + 3 + 1 = 12.

Try It Yourself
redirect icon

Checking Every Path - O(n * h) Time and O(n) Space

The idea is to check of all possible path from root to leaf recursively. So we check for every path that is from root to every leaf and take the sum which path has the maximum sum.

Follow the steps below to solve the problem:

  • Traverse the binary tree from root to every node and maintain a parent map which contains the parent of a node.
  • While traversing, if the current node don't has left or right child, then the node is a leaf node.
  • When we encounter a leaf node, call a separate function which calculates the sum from that leaf to root.
  • The function calculates the sum by using parent map by recursively calling the function with parent node until we reach root.
  • Maintain a variable which keeps and updates the maximum sum.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;
    Node(int x)
    {
        data = x;
        left = right = nullptr;
    }
};

// Helper function to calculate the sum
// from a leaf node to the root
int getSumOfPath(Node *root, unordered_map<Node *, Node *> &parent)
{

    // If the current node has no parent,
    // return its data (it's the root)
    if (parent.find(root) == parent.end())
        return root->data;

    // Recursively sum the current node data
    // with its parent's path sum
    return root->data + getSumOfPath(parent[root], parent);
}

// Function to calculate the maximum leaf-to-root path sum
void sumCal(Node *root, int &maxx, unordered_map<Node *, Node *> &parent)
{

    // Check if the current node is a leaf node
    if (root->left == nullptr && root->right == nullptr)
    {

        // Update the maximum sum if the
        // current path's sum is greater
        maxx = max(maxx, getSumOfPath(root, parent));
        return;
    }

    // If the left child exists, set the
    // current node as its parent and recurse
    if (root->left)
    {
        parent[root->left] = root;
        sumCal(root->left, maxx, parent);
    }

    // If the right child exists, set the
    // current node as its parent and recurse
    if (root->right)
    {
        parent[root->right] = root;
        sumCal(root->right, maxx, parent);
    }
}

// Function to return the maximum leaf-
// to-root path sum in the binary tree
int maxPathSum(Node *root)
{

    // To store each node's parent for path calculation
    unordered_map<Node *, Node *> parent;

    // Variable to store the maximum sum
    int maxx = INT_MIN;

    // Recursively calculate the sum for all paths
    sumCal(root, maxx, parent);

    // Return the maximum path sum found
    return maxx;
}

// Driver Code
int main()
{

    // Constructing tree
    //             1
    //           /   \
    //          2     3
    //         / \     \
    //        4   5     8
    //         \       / \
    //          2     6   7

    Node *root = new Node(1);

    root->left = new Node(2);
    root->right = new Node(3);

    root->left->left = new Node(4);
    root->left->right = new Node(5);

    root->left->left->right = new Node(2);

    root->right->right = new Node(8);

    root->right->right->left = new Node(6);
    root->right->right->right = new Node(7);

    int sum = maxPathSum(root);

    cout << sum << endl;

    return 0;
}
Java
import java.util.HashMap;

class Node {
    public int data;
    public Node left;
    public Node right;
    public Node(int x)
    {
        data = x;
        left = right = null;
    }
}

public class GfG {
    // Helper function to calculate the sum
    // from a leaf node to the root
    public static int
    getSumOfPath(Node root, HashMap<Node, Node> parent)
    {
        // If the current node has no parent,
        // return its data (it's the root)
        if (!parent.containsKey(root))
            return root.data;

        // Recursively sum the current node data
        // with its parent's path sum
        return root.data
            + getSumOfPath(parent.get(root), parent);
    }

    // Function to calculate the maximum leaf-to-root path
    // sum
    public static void sumCal(Node root, int[] maxx,
                              HashMap<Node, Node> parent)
    {
        // Check if the current node is a leaf node
        if (root.left == null && root.right == null) {
            // Update the maximum sum if the
            // current path's sum is greater
            maxx[0] = Math.max(maxx[0],
                               getSumOfPath(root, parent));
            return;
        }

        // If the left child exists, set the
        // current node as its parent and recurse
        if (root.left != null) {
            parent.put(root.left, root);
            sumCal(root.left, maxx, parent);
        }

        // If the right child exists, set the
        // current node as its parent and recurse
        if (root.right != null) {
            parent.put(root.right, root);
            sumCal(root.right, maxx, parent);
        }
    }

    // Function to return the maximum leaf-
    // to-root path sum in the binary tree
    public static int maxPathSum(Node root)
    {
        // To store each node's parent for path calculation
        HashMap<Node, Node> parent = new HashMap<>();

        // Variable to store the maximum sum
        int[] maxx = { Integer.MIN_VALUE };

        // Recursively calculate the sum for all paths
        sumCal(root, maxx, parent);

        // Return the maximum path sum found
        return maxx[0];
    }

    // Driver Code
    public static void main(String[] args)
    {
        // Constructing tree
        //             1
        //           /   \
        //          2     3
        //         / \     \
        //        4   5     8
        //         \       / \\
        //          2     6   7

        Node root = new Node(1);

        root.left = new Node(2);
        root.right = new Node(3);

        root.left.left = new Node(4);
        root.left.right = new Node(5);

        root.left.left.right = new Node(2);

        root.right.right = new Node(8);

        root.right.right.left = new Node(6);
        root.right.right.right = new Node(7);

        int sum = maxPathSum(root);

        System.out.println(sum);
    }
}
Python
from collections import defaultdict


class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Helper function to calculate the sum
# from a leaf node to the root


def get_sum_of_path(root, parent):
    # If the current node has no parent,
    # return its data (it's the root)
    if root not in parent:
        return root.data

    # Recursively sum the current node data
    # with its parent's path sum
    return root.data + get_sum_of_path(parent[root], parent)

# Function to calculate the maximum leaf-to-root path sum


def sum_cal(root, maxx, parent):
    # Check if the current node is a leaf node
    if root.left is None and root.right is None:
        # Update the maximum sum if the
        # current path's sum is greater
        maxx[0] = max(maxx[0], get_sum_of_path(root, parent))
        return

    # If the left child exists, set the
    # current node as its parent and recurse
    if root.left:
        parent[root.left] = root
        sum_cal(root.left, maxx, parent)

    # If the right child exists, set the
    # current node as its parent and recurse
    if root.right:
        parent[root.right] = root
        sum_cal(root.right, maxx, parent)

# Function to return the maximum leaf-
# to-root path sum in the binary tree


def maxPathSum(root):
    # To store each node's parent for path calculation
    parent = defaultdict(None)

    # Variable to store the maximum sum
    maxx = [float('-inf')]

    # Recursively calculate the sum for all paths
    sum_cal(root, maxx, parent)

    # Return the maximum path sum found
    return maxx[0]


# Driver Code
if __name__ == '__main__':
    # Constructing tree
    #             1
    #           /   \
    #          2     3
    #         / \     \
    #        4   5     8
    #         \       / \\
    #          2     6   7

    root = Node(1)

    root.left = Node(2)
    root.right = Node(3)

    root.left.left = Node(4)
    root.left.right = Node(5)

    root.left.left.right = Node(2)

    root.right.right = Node(8)

    root.right.right.left = Node(6)
    root.right.right.right = Node(7)

    sum = maxPathSum(root)

    print(sum)
C#
using System;
using System.Collections.Generic;

public class Node {
    public int data;
    public Node left;
    public Node right;
    public Node(int x)
    {
        data = x;
        left = right = null;
    }
}

public class GfG {
    // Helper function to calculate the sum
    // from a leaf node to the root
    public static int
    getSumOfPath(Node root, Dictionary<Node, Node> parent)
    {
        // If the current node has no parent,
        // return its data (it's the root)
        if (!parent.ContainsKey(root))
            return root.data;

        // Recursively sum the current node data
        // with its parent's path sum
        return root.data
            + getSumOfPath(parent[root], parent);
    }

    // Function to calculate the maximum leaf-to-root path
    // sum
    public static void sumCal(Node root, ref int maxx,
                              Dictionary<Node, Node> parent)
    {
        // Check if the current node is a leaf node
        if (root.left == null && root.right == null) {
            // Update the maximum sum if the
            // current path's sum is greater
            maxx = Math.Max(maxx,
                            getSumOfPath(root, parent));
            return;
        }

        // If the left child exists, set the
        // current node as its parent and recurse
        if (root.left != null) {
            parent[root.left] = root;
            sumCal(root.left, ref maxx, parent);
        }

        // If the right child exists, set the
        // current node as its parent and recurse
        if (root.right != null) {
            parent[root.right] = root;
            sumCal(root.right, ref maxx, parent);
        }
    }

    // Function to return the maximum leaf-
    // to-root path sum in the binary tree
    public static int maxPathSum(Node root)
    {
        // To store each node's parent for path calculation
        Dictionary<Node, Node> parent
            = new Dictionary<Node, Node>();

        // Variable to store the maximum sum
        int maxx = int.MinValue;

        // Recursively calculate the sum for all paths
        sumCal(root, ref maxx, parent);

        // Return the maximum path sum found
        return maxx;
    }

    // Driver Code
    public static void Main()
    {
        // Constructing tree
        //             1
        //           /   \
        //          2     3
        //         / \     \
        //        4   5     8
        //         \       / \
        //          2     6   7

        Node root = new Node(1);

        root.left = new Node(2);
        root.right = new Node(3);

        root.left.left = new Node(4);
        root.left.right = new Node(5);

        root.left.left.right = new Node(2);

        root.right.right = new Node(8);

        root.right.right.left = new Node(6);
        root.right.right.right = new Node(7);

        int sum = maxPathSum(root);

        Console.WriteLine(sum);
    }
}
JavaScript
// Node class
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Helper function to calculate the sum
// from a leaf node to the root
function getSumOfPath(root, parent)
{

    // If the current node has no parent,
    // return its data (it's the root)
    if (!parent.has(root))
        return root.data;

    // Recursively sum the current node data
    // with its parent's path sum
    return root.data +
           getSumOfPath(parent.get(root), parent);
}

// Function to calculate the maximum leaf-to-root path sum
function sumCal(root, maxx, parent)
{

    // Check if the current node is a leaf node
    if (!root.left && !root.right)
    {

        // Update the maximum sum if the
        // current path's sum is greater
        maxx.val = Math.max(
            maxx.val,
            getSumOfPath(root, parent)
        );

        return;
    }

    // If the left child exists, set the
    // current node as its parent and recurse
    if (root.left)
    {
        parent.set(root.left, root);
        sumCal(root.left, maxx, parent);
    }

    // If the right child exists, set the
    // current node as its parent and recurse
    if (root.right)
    {
        parent.set(root.right, root);
        sumCal(root.right, maxx, parent);
    }
}

// Function to return the maximum leaf-
// to-root path sum in the binary tree
function maxPathSum(root)
{

    // To store each node's parent for path calculation
    let parent = new Map();

    // Variable to store the maximum sum
    let maxx = { val: Number.MIN_SAFE_INTEGER };

    // Recursively calculate the sum for all paths
    sumCal(root, maxx, parent);

    // Return the maximum path sum found
    return maxx.val;
}

// Driver Code

// Constructing tree
//             1
//           /   \
//          2     3
//         / \     \
//        4   5     8
//         \       / \
//          2     6   7

let root = new Node(1);

root.left = new Node(2);
root.right = new Node(3);

root.left.left = new Node(4);
root.left.right = new Node(5);

root.left.left.right = new Node(2);

root.right.right = new Node(8);

root.right.right.left = new Node(6);
root.right.right.right = new Node(7);

let sum = maxPathSum(root);

console.log(sum);

Output
19

Time Complexity: O(n * h) Where n is number of nodes in tree and h is height of tree.
Auxiliary Space: O(n)

Keeping Track of Maximum Sum - O(n) Time and O(h) Space

The idea is to keep track of current sum and maximum sum while traversing the tree and update maximum sum if at leaf node current sum is greater them maximum sum.

Follow the steps below to solve the problem:

  • If the node is the root, return its data.
  • If the node is a leaf, Check where current sum is greater than maximum sum, then update maximum sum.
  • For non-leaf nodes, update current sum and make recursive call on both left and right child.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;
    Node(int x)
    {
        data = x;
        left = right = nullptr;
    }
};

// Helper function to find the leaf node that contributes
// to the maximum sum and returns the maximum sum from the
// root to that leaf
void findMaxSum(Node *root, int currSum, int &mxSum)
{
    if (root == nullptr)
        return;

    // Add the current node's data to the path sum
    currSum += root->data;

    // Check if this node is a leaf node
    if (root->left == nullptr && root->right == nullptr)
    {

        // Update the maximum sum and target
        // leaf if a higher sum is found
        if (currSum > mxSum)
        {
            mxSum = currSum;
        }
    }

    // Recursively check for the maximum sum
    // in the left and right subtrees
    findMaxSum(root->left, currSum, mxSum);
    findMaxSum(root->right, currSum, mxSum);
}

// Function to return the maximum sum
// path from root to leaf
int maxPathSum(Node *root)
{

    // empty tree has sum 0
    if (root == nullptr)
        return 0;

    // Initialize max sum as the smallest possible integer
    int mxSum = INT_MIN;

    // Find the target leaf and maximum sum
    findMaxSum(root, 0, mxSum);

    // Return the maximum sum found
    return mxSum;
}

// Driver Code
int main()
{

    // Constructing tree
    //             1
    //           /   \
    //          2     3
    //         / \     \
    //        4   5     8
    //         \       / \
    //          2     6   7

    Node *root = new Node(1);

    root->left = new Node(2);
    root->right = new Node(3);

    root->left->left = new Node(4);
    root->left->right = new Node(5);

    root->left->left->right = new Node(2);

    root->right->right = new Node(8);

    root->right->right->left = new Node(6);
    root->right->right->right = new Node(7);

    int sum = maxPathSum(root);

    cout << sum << endl;

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left, right;

    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

public class GfG {

    // Helper function to find the leaf node that
    // contributes to the maximum sum and returns the
    // maximum sum from the root to that leaf
    void findMaxSum(Node node, int currSum, int[] maxSum)
    {
        if (node == null)
            return;

        // Add the current node's data to the path sum
        currSum += node.data;

        // Check if this node is a leaf node
        if (node.left == null && node.right == null) {

            // Update the maximum sum and target
            // leaf if a higher sum is found
            if (currSum > maxSum[0]) {
                maxSum[0] = currSum;
            }
        }

        // Recursively check for the maximum sum
        // in the left and right subtrees
        findMaxSum(node.left, currSum, maxSum);
        findMaxSum(node.right, currSum, maxSum);
    }

    // Function to return the maximum sum
    // path from root to leaf
    int maxPathSum(Node node)
    {
        // empty tree has sum 0
        if (node == null)
            return 0;

        // Initialize max sum as the smallest possible
        // integer
        int[] maxSum = { Integer.MIN_VALUE };

        // Find the target leaf and maximum sum
        findMaxSum(node, 0, maxSum);

        // Return the maximum sum found
        return maxSum[0];
    }

    public static void main(String[] args)
    {
        GfG tree = new GfG();

        // Constructing tree
        //             1
        //           /   \
        //          2     3
        //         / \     \
        //        4   5     8
        //         \       / \
        //          2     6   7

        Node root = new Node(1);

        root.left = new Node(2);
        root.right = new Node(3);

        root.left.left = new Node(4);
        root.left.right = new Node(5);

        root.left.left.right = new Node(2);

        root.right.right = new Node(8);

        root.right.right.left = new Node(6);
        root.right.right.right = new Node(7);

        int sum = tree.maxPathSum(root);

        System.out.println(sum);
    }
}
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Helper function to find the leaf node that contributes
# to the maximum sum and returns the maximum sum from the
# root to that leaf
def findMaxSum(root, currSum, mxSum):
    if root is None:
        return

    # Add the current node's data to the path sum
    currSum += root.data

    # Check if this node is a leaf node
    if root.left is None and root.right is None:

        # Update the maximum sum and target
        # leaf if a higher sum is found
        if currSum > mxSum[0]:
            mxSum[0] = currSum

    # Recursively check for the maximum sum
    # in the left and right subtrees
    findMaxSum(root.left, currSum, mxSum)
    findMaxSum(root.right, currSum, mxSum)

# Function to return the maximum sum
# path from root to leaf
def maxPathSum(root):

    # empty tree has sum 0
    if root is None:
        return 0

    # Initialize max sum as the smallest possible integer
    mxSum = [float('-inf')]

    # Find the target leaf and maximum sum
    findMaxSum(root, 0, mxSum)

    # Return the maximum sum found
    return mxSum[0]

# Driver Code
if __name__ == '__main__':

    # Constructing tree
    #             1
    #           /   \
    #          2     3
    #         / \     \
    #        4   5     8
    #         \       / \\
    #          2     6   7

    root = Node(1)

    root.left = Node(2)
    root.right = Node(3)

    root.left.left = Node(4)
    root.left.right = Node(5)

    root.left.left.right = Node(2)

    root.right.right = Node(8)

    root.right.right.left = Node(6)
    root.right.right.right = Node(7)

    sum = maxPathSum(root)

    print(sum)
C#
using System;

public class Node
{
  public int data;
  public Node left;
  public Node right;
  public Node(int x)
  {
      data = x;
      left = right = null;
  }
}

public class GfG
{
  // Helper function to find the leaf node that contributes
  // to the maximum sum and returns the maximum sum from the
  // root to that leaf
  static void findMaxSum(Node root, int currSum, ref int mxSum)
  {
      if (root == null)
          return;

      // Add the current node's data to the path sum
      currSum += root.data;

      // Check if this node is a leaf node
      if (root.left == null && root.right == null)
      {
          // Update the maximum sum and target
          // leaf if a higher sum is found
          if (currSum > mxSum)
         {
              mxSum = currSum;
          }
      }

      // Recursively check for the maximum sum
      // in the left and right subtrees
      findMaxSum(root.left, currSum, ref mxSum);
      findMaxSum(root.right, currSum, ref mxSum);
  }

  // Function to return the maximum sum
  // path from root to leaf
  static int maxPathSum(Node root)
  {
      // empty tree has sum 0
      if (root == null)
          return 0;

      // Initialize max sum as the smallest possible integer
      int mxSum = int.MinValue;

      // Find the target leaf and maximum sum
      findMaxSum(root, 0, ref mxSum);

      // Return the maximum sum found
      return mxSum;
  }

  // Driver Code
  public static void Main()
  {
      // Constructing tree
      //             1
      //           /   \
      //          2     3
      //         / \     \
      //        4   5     8
      //         \       / \\
      //          2     6   7

      Node root = new Node(1);

      root.left = new Node(2);
      root.right = new Node(3);

      root.left.left = new Node(4);
      root.left.right = new Node(5);

      root.left.left.right = new Node(2);

      root.right.right = new Node(8);

      root.right.right.left = new Node(6);
      root.right.right.right = new Node(7);

      int sum = maxPathSum(root);

      Console.WriteLine(sum);
  }
}
JavaScript
// Helper function to find the leaf node that contributes
// to the maximum sum and returns the maximum sum from the
// root to that leaf
function findMaxSum(root, currSum, mxSum) {
    if (root === null)
        return;

    // Add the current node's data to the path sum
    currSum += root.data;

    // Check if this node is a leaf node
    if (root.left === null && root.right === null) {

        // Update the maximum sum and target
        // leaf if a higher sum is found
        if (currSum > mxSum)
            mxSum[0] = currSum;
    }

    // Recursively check for the maximum sum
    // in the left and right subtrees
    findMaxSum(root.left, currSum, mxSum);
    findMaxSum(root.right, currSum, mxSum);
}

// Function to return the maximum sum
// path from root to leaf
function maxPathSum(root) {

    // empty tree has sum 0
    if (root === null)
        return 0;

    // Initialize max sum as the smallest possible integer
    let mxSum = [Number.NEGATIVE_INFINITY];

    // Find the target leaf and maximum sum
    findMaxSum(root, 0, mxSum);

    // Return the maximum sum found
    return mxSum[0];
}

// Driver Code
// Constructing tree
//             1
//           /   \
//          2     3
//         / \     \
//        4   5     8
//         \       / \\
//          2     6   7

class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

let root = new Node(1);

root.left = new Node(2);
root.right = new Node(3);

root.left.left = new Node(4);
root.left.right = new Node(5);

root.left.left.right = new Node(2);

root.right.right = new Node(8);

root.right.right.left = new Node(6);
root.right.right.right = new Node(7);

let sum = maxPathSum(root);

console.log(sum);

Output
19

Time Complexity: O(n) Where n is number of nodes in tree.
Auxiliary Space: O(h), where h is height of tree.

Comment