Given a binary tree, write an efficient algorithm to find the maximum sum root-to-leaf path, i.e., the maximum sum path from the root node to any leaf node in it.

For example, consider the following tree. The maximum sum is 18, and the maximum sum path is [1, 3, 5, 9].

 
Maximum Sum Root to Leaf Path

Practice this problem

The problem can be divided further into two subproblems:

  1. Calculate the maximum sum from the root node to any leaf node in a binary tree.
  2. Print root-to-leaf path having maximum sum in a binary tree.

We can solve both problems in linear time by traversing the tree in a bottom-up manner (postorder fashion). Following is a simple implementation in C++, Java, and Python based on the idea:

C++


Download  Run Code

Output:

The maximum sum is 18
The maximum sum path is 9 5 3 1

Java


Download  Run Code

Output:

The maximum sum is 18
The maximum sum path is 9 5 3 1

Python


Download  Run Code

Output:

The maximum sum is 18
The maximum sum path is 9 5 3 1

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.