Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
All nodes between two given levels in Binary Tree
Next article icon

Minimum sum path between two leaves of a binary tree

Last Updated : 06 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 -> 1  Input :         3        /  \       2    4      / \      -5  1 Output : -2


 


Approach: The idea is to maintain two values in recursive calls: 
 

  1. Minimum root to leaf path sum for the subtree rooted under current node.
  2. The minimum path sum between leaves.


For every visited node X, we find the minimum root to leaf sum in left and right sub trees of X. We add the two values with X's data, and compare the sum with the current minimum path sum.
Below is the implementation of the above approach: 
 

C++
// C++ program to find minimum 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;     struct Node* 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); }  // A utility function to find the minimum sum between // any two leaves. This function calculates two values: // 1. Minimum path sum between two leaves which is stored // in result and, // 2. The minimum root to leaf path sum which is returned. // If one side of root is empty, then it returns INT_MIN int minPathSumUtil(struct Node* root, int& result) {     // Base cases     if (root == NULL)         return 0;      if (root->left == NULL && root->right == NULL)         return root->data;      // Find minimum sum in left and right sub tree. Also     // find minimum root to leaf sums in left and right     // sub trees and store them in ls and rs     int ls = minPathSumUtil(root->left, result);     int rs = minPathSumUtil(root->right, result);      // If both left and right children exist     if (root->left && root->right) {         // Update result if needed         result = min(result, ls + rs + root->data);          // Return minimum possible value for root being         // on one side         return min(ls + root->data, rs + root->data);     }      // If any of the two children is empty, return     // root sum for root being on one side     if (root->left == NULL)         return rs + root->data;     else         return ls + root->data; }  // Function to return the minimum // sum path between two leaves int minPathSum(struct Node* root) {     int result = INT_MAX;     minPathSumUtil(root, result);     return result; }  // Driver code int main() {     struct Node* root = newNode(4);     root->left = newNode(5);     root->right = newNode(-6);     root->left->left = newNode(2);     root->left->right = newNode(-3);     root->right->left = newNode(1);     root->right->right = newNode(8);      cout << minPathSum(root);      return 0; } 
Java
// Java program to find minimum path sum  // between two leaves of a binary tree  class GFG {      // A binary tree node  static class Node  {      int data;      Node left;      Node right;  };   // Utility function to allocate memory  // for a new node  static Node newNode(int data)  {      Node node = new Node();      node.data = data;      node.left = node.right = null;       return (node);  }  static int result;  // A utility function to find the minimum sum between  // any two leaves. This function calculates two values:  // 1. Minimum path sum between two leaves which is stored  // in result and,  // 2. The minimum root to leaf path sum which is returned.  // If one side of root is empty, then it returns INT_MIN  static int minPathSumUtil( Node root)  {      // Base cases      if (root == null)          return 0;       if (root.left == null && root.right == null)          return root.data;       // Find minimum sum in left and right sub tree. Also      // find minimum root to leaf sums in left and right      // sub trees and store them in ls and rs      int ls = minPathSumUtil(root.left);      int rs = minPathSumUtil(root.right);       // If both left and right children exist      if (root.left != null && root.right != null)      {          // Update result if needed          result = Math.min(result, ls + rs + root.data);           // Return minimum possible value for root being          // on one side          return Math.min(ls + root.data, rs + root.data);      }       // If any of the two children is empty, return      // root sum for root being on one side      if (root.left == null)          return rs + root.data;      else         return ls + root.data;  }   // Function to return the minimum  // sum path between two leaves  static int minPathSum( Node root)  {      result = Integer.MAX_VALUE;      minPathSumUtil(root);      return result;  }    // Driver code  public static void main(String args[]) {      Node root = newNode(4);      root.left = newNode(5);      root.right = newNode(-6);      root.left.left = newNode(2);      root.left.right = newNode(-3);      root.right.left = newNode(1);      root.right.right = newNode(8);       System.out.print(minPathSum(root));  } }   // This code is contributed by Arnab Kundu 
Python3
# Python3 program to find minimum path sum  # between two leaves of a binary tree       # Tree node  class Node:      def __init__(self, data):          self.data = data          self.left = None         self.right = None  # Utility function to allocate memory  # for a new node  def newNode( data):       node = Node(0)      node.data = data      node.left = node.right = None      return (node)   result = -1  # A utility function to find the  # minimum sum between any two leaves. # This function calculates two values:  # 1. Minimum path sum between two leaves   # which is stored in result and,  # 2. The minimum root to leaf path sum  # which is returned.  # If one side of root is empty,  # then it returns INT_MIN  def minPathSumUtil(root) :     global result          # Base cases      if (root == None):          return 0      if (root.left == None and          root.right == None) :         return root.data       # Find minimum sum in left and right sub tree.      # Also find minimum root to leaf sums in      # left and right sub trees and store them      # in ls and rs      ls = minPathSumUtil(root.left)      rs = minPathSumUtil(root.right)       # If both left and right children exist      if (root.left != None and          root.right != None) :              # Update result if needed          result = min(result, ls +                       rs + root.data)           # Return minimum possible value for          # root being on one side          return min(ls + root.data,                     rs + root.data)           # If any of the two children is empty,      # return root sum for root being on one side      if (root.left == None) :         return rs + root.data      else:         return ls + root.data   # Function to return the minimum  # sum path between two leaves  def minPathSum( root):      global result     result = 9999999     minPathSumUtil(root)      return result   # Driver code  root = newNode(4)  root.left = newNode(5)  root.right = newNode(-6)  root.left.left = newNode(2)  root.left.right = newNode(-3)  root.right.left = newNode(1)  root.right.right = newNode(8)   print(minPathSum(root))   # This code is contributed  # by Arnab Kundu 
C#
// C# program to find minimum path sum  // between two leaves of a binary tree  using System;      class GFG {      // A binary tree node  public class Node  {      public int data;      public Node left;      public Node right;  };   // Utility function to allocate memory  // for a new node  static Node newNode(int data)  {      Node node = new Node();      node.data = data;      node.left = node.right = null;       return (node);  }  static int result;  // A utility function to find the minimum sum between  // any two leaves. This function calculates two values:  // 1. Minimum path sum between two leaves which is stored  // in result and,  // 2. The minimum root to leaf path sum which is returned.  // If one side of root is empty, then it returns INT_MIN  static int minPathSumUtil( Node root)  {      // Base cases      if (root == null)          return 0;       if (root.left == null && root.right == null)          return root.data;       // Find minimum sum in left and right sub tree. Also      // find minimum root to leaf sums in left and right      // sub trees and store them in ls and rs      int ls = minPathSumUtil(root.left);      int rs = minPathSumUtil(root.right);       // If both left and right children exist      if (root.left != null && root.right != null)      {          // Update result if needed          result = Math.Min(result, ls + rs + root.data);           // Return minimum possible value for root being          // on one side          return Math.Min(ls + root.data, rs + root.data);      }       // If any of the two children is empty, return      // root sum for root being on one side      if (root.left == null)          return rs + root.data;      else         return ls + root.data;  }   // Function to return the minimum  // sum path between two leaves  static int minPathSum( Node root)  {      result = int.MaxValue;      minPathSumUtil(root);      return result;  }    // Driver code  public static void Main(String []args) {      Node root = newNode(4);      root.left = newNode(5);      root.right = newNode(-6);      root.left.left = newNode(2);      root.left.right = newNode(-3);      root.right.left = newNode(1);      root.right.right = newNode(8);   Console.Write(minPathSum(root));  } }  // This code has been contributed by 29AjayKumar  
JavaScript
<script>      // JavaScript program to find minimum path sum      // between two leaves of a binary tree           // Structure of binary tree     class Node     {         constructor(data) {            this.left = null;            this.right = null;            this.data = data;         }     }          // Utility function to allocate memory      // for a new node      function newNode(data)      {          let node = new Node(data);          return (node);      }      let result;      // A utility function to find the minimum sum between      // any two leaves. This function calculates two values:      // 1. Minimum path sum between two leaves which is stored      // in result and,      // 2. The minimum root to leaf path sum which is returned.      // If one side of root is empty, then it returns INT_MIN      function minPathSumUtil(root)      {          // Base cases          if (root == null)              return 0;           if (root.left == null && root.right == null)              return root.data;           // Find minimum sum in left and right sub tree. Also          // find minimum root to leaf sums in left and right          // sub trees and store them in ls and rs          let ls = minPathSumUtil(root.left);          let rs = minPathSumUtil(root.right);           // If both left and right children exist          if (root.left != null && root.right != null)          {              // Update result if needed              result = Math.min(result, ls + rs + root.data);               // Return minimum possible value for root being              // on one side              return Math.min(ls + root.data, rs + root.data);          }           // If any of the two children is empty, return          // root sum for root being on one side          if (root.left == null)              return rs + root.data;          else             return ls + root.data;      }       // Function to return the minimum      // sum path between two leaves      function minPathSum(root)      {          result = Number.MAX_VALUE;          minPathSumUtil(root);          return result;      }          let root = newNode(4);      root.left = newNode(5);      root.right = newNode(-6);      root.left.left = newNode(2);      root.left.right = newNode(-3);      root.right.left = newNode(1);      root.right.right = newNode(8);         document.write(minPathSum(root));       </script> 

Output: 
1

 

Time Complexity: O(N) 
Auxiliary Space: O(N)


Next Article
All nodes between two given levels in Binary Tree
author
sakshi_srivastava
Improve
Article Tags :
  • Tree
  • Data Structures
  • DSA
  • Binary Tree
Practice Tags :
  • Data Structures
  • Tree

Similar Reads

  • Print nodes between two given level numbers of a binary tree
    Given a binary tree and two level numbers 'low' and 'high', print nodes from level low to level high. For example consider the binary tree given in below diagram. Input: Root of below tree, low = 2, high = 4 Output: 8 22 4 12 10 14 A Simple Method is to first write a recursive function that prints n
    10 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 tw
    12 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
    8 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 op
    15 min read
  • Print all nodes between two given levels in Binary Tree
    Given a binary tree, the task is to print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. Note: The levels are 1-indexed, i.e., root node is at level 1. Example: Input: Binary tree, l = 2, h = 3 Outp
    8 min read
  • Find distance between two nodes of a Binary Tree
    Given a Binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from another. The given two nodes are guaranteed to be in the binary tree and all nod
    15+ min read
  • Shortest distance between two nodes in an infinite binary tree
    Consider you have an infinitely long binary tree having a pattern as below: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ . . . . . . . . Given two nodes with values x and y. The task is to find the length of the shortest path between the two nodes. Examples: Input: x = 2, y = 3 Output: 2 Input: x = 4,
    15 min read
  • Queries to find distance between two nodes of a Binary tree
    Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from other. We have already discussed a method which uses segment tree to reduce the
    15+ min read
  • Count of 1's in any path in a Binary Tree
    Given a binary tree of 0s and 1s, the task is to find the maximum number of 1s in any path in the tree. The path may start and end at any node in the tree.Example: Input: 1 / \ 0 1 / \ 1 1 / \ 1 0 Output: 4 Approach: A function countUntil has been created which returns the maximum count of 1 in any
    10 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
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences