Root to leaf path sum equal to a given number

Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number. Return false if no such path can be found. 
 

For example, in the above tree root to leaf paths exist with following sums.
21 –> 10 – 8 – 3 
23 –> 10 – 8 – 5 
14 –> 10 – 2 – 2
So the returned value should be true only for numbers 21, 23 and 14. For any other number, returned value should be false.

Algorithm: 
Recursively check if left or right child has path sum equal to ( number – value at current node)
Implementation:  

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
#define bool int
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node
{
    public:
    int data;
    node* left;
    node* right;
};
 
/*
Given a tree and a sum, return true if there is a path from the root
down to a leaf, such that adding up all the values along the path
equals the given sum.
 
Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/
bool hasPathSum(node* Node, int sum)
{
    /* return true if we run out of tree and sum==0 */
    if (Node == NULL)
    {
        return (sum == 0);
    }
     
    else
    {
        bool ans = 0;
     
        int subSum = sum - Node->data;
     
        /* If we reach a leaf node and sum becomes 0 then return true*/
        if ( subSum == 0 && Node->left == NULL && Node->right == NULL )
        return 1;
         
        /* otherwise check both subtrees */
        if(Node->left)
            ans = ans || hasPathSum(Node->left, subSum);
        if(Node->right)
            ans = ans || hasPathSum(Node->right, subSum);
     
        return ans;
    }
}
 
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newnode(int data)
{
    node* Node = new node();
    Node->data = data;
    Node->left = NULL;
    Node->right = NULL;
     
    return(Node);
}
 
// Driver Code
int main()
{
 
    int sum = 21;
     
    /* Constructed binary tree is
                10
            / \
            8 2
        / \ /
        3 5 2
    */
    node *root = newnode(10);
    root->left = newnode(8);
    root->right = newnode(2);
    root->left->left = newnode(3);
    root->left->right = newnode(5);
    root->right->left = newnode(2);
     
    if(hasPathSum(root, sum))
        cout << "There is a root-to-leaf path with sum " << sum;
    else
        cout << "There is no root-to-leaf path with sum " << sum;
     
    return 0;
}
 
// This code is contributed by rathbhupendra

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
#include <stdlib.h>
#define bool int
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
/*
 Given a tree and a sum, return
 true if there is a path from
 the root down to a leaf, such
 that adding up all the values
 along the path equals the given sum.
 
 Strategy: subtract the node
 value from the sum when
 recurring down, and check to
 see if the sum is 0 when you
 run out of tree.
*/
bool hasPathSum(struct node* node, int sum)
{
    /* return true if we run
    out of tree and sum==0 */
    if (node == NULL) {
        return (sum == 0);
    }
 
    else {
        bool ans = 0;
 
        int subSum = sum - node->data;
 
        /* If we reach a leaf node
        and sum becomes 0 then
         * return true*/
        if (subSum == 0 && node->left == NULL
            && node->right == NULL)
            return 1;
 
        /* otherwise check both subtrees */
        if (node->left)
            ans = ans
                  || hasPathSum(node->left, subSum);
        if (node->right)
            ans = ans
                || hasPathSum(node->right, subSum);
 
        return ans;
    }
}
 
/* UTILITY FUNCTIONS */
/* Helper function that
   allocates a new node with the
   given data and NULL left
   and right pointers. */
struct node* newnode(int data)
{
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
// Driver Code
int main()
{
 
    int sum = 21;
 
    /* Constructed binary tree is
              10
            /   \
          8      2
        /  \    /
      3     5  2
    */
    struct node* root = newnode(10);
    root->left = newnode(8);
    root->right = newnode(2);
    root->left->left = newnode(3);
    root->left->right = newnode(5);
    root->right->left = newnode(2);
 
    if (hasPathSum(root, sum))
        printf("There is a root-to-leaf path with sum %d",
               sum);
    else
        printf("There is no root-to-leaf path with sum %d",
               sum);
 
    getchar();
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print to print
// root to leaf path sum
// equal to a given number
 
/* A binary tree node has data,
 pointer to left child
   and a pointer to right child */
class Node {
    int data;
    Node left, right;
 
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
class BinaryTree {
 
    Node root;
 
    /*
     Given a tree and a sum,
     return true if there is a path
     from the root down to a leaf,
     such that adding up all
     the values along the path
     equals the given sum.
 
     Strategy: subtract the node
     value from the sum when
     recurring down, and check to
     see if the sum is 0 when
     you run out of tree.
     */
 
    boolean hasPathSum(Node node, int sum)
    {
        if (node == null)
            return sum == 0;
        return hasPathSum(node.left, sum - node.data)
            || hasPathSum(node.right, sum - node.data);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int sum = 21;
 
        /* Constructed binary tree is
              10
             /  \
           8     2
          / \   /
         3   5 2
        */
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(8);
        tree.root.right = new Node(2);
        tree.root.left.left = new Node(3);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(2);
 
        if (tree.haspathSum(tree.root, sum))
            System.out.println(
                "There is a root to leaf path with sum "
                + sum);
        else
            System.out.println(
                "There is no root to leaf path with sum "
                + sum);
    }
}
 
// This code has been contributed by Mayank
// Jaiswal(mayank_24)

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find if
# there is a root to sum path
 
# 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
 
 
"""
 Given a tree and a sum, return
 true if there is a path from the root
 down to a leaf, such that
 adding up all the values along the path
 equals the given sum.
  
 Strategy: subtract the node
 value from the sum when recurring down,
 and check to see if the sum
 is 0 when you run out of tree.
"""
# s is the sum
 
 
def hasPathSum(node, s):
 
    # Return true if we run out of tree and s = 0
    if node is None:
        return (s == 0)
 
    else:
        ans = 0
 
        subSum = s - node.data
 
        # If we reach a leaf node and sum becomes 0, then
        # return True
        if(subSum == 0 and node.left == None and node.right == None):
            return True
 
        # Otherwise check both subtrees
        if node.left is not None:
            ans = ans or hasPathSum(node.left, subSum)
        if node.right is not None:
            ans = ans or hasPathSum(node.right, subSum)
 
        return ans
 
# Driver Code
 
 
s = 21
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.right = Node(5)
root.left.left = Node(3)
root.right.left = Node(2)
 
if hasPathSum(root, s):
    print "There is a root-to-leaf path with sum %d" % (s)
else:
    print "There is no root-to-leaf path with sum %d" % (s)
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to print to print root to
// leaf path sum equal to a given number
using System;
 
/* A binary tree node has data, pointer
to left child and a pointer to right child */
public class Node {
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
class GFG {
    public Node root;
 
    /*
    Given a tree and a sum, return true if
    there is a path from the root down to a
    leaf, such that adding up all the values
    along the path equals the given sum.
 
    Strategy: subtract the node value from the
    sum when recurring down, and check to see
    if the sum is 0 when you run out of tree.
    */
 
    public virtual bool haspathSum(Node node, int sum)
    {
        if (node == null) {
            return (sum == 0);
        }
        else {
            bool ans = false;
 
            int subsum = sum - node.data;
            if (subsum == 0 && node.left == null
                && node.right == null) {
                return true;
            }
 
            /* otherwise check both subtrees */
            if (node.left != null) {
                ans = ans || haspathSum(node.left, subsum);
            }
            if (node.right != null) {
                ans = ans || haspathSum(node.right, subsum);
            }
            return ans;
        }
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int sum = 21;
 
        /* Constructed binary tree is
            10
            / \
        8     2
        / \ /
        3 5 2
        */
        GFG tree = new GFG();
        tree.root = new Node(10);
        tree.root.left = new Node(8);
        tree.root.right = new Node(2);
        tree.root.left.left = new Node(3);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(2);
 
        if (tree.haspathSum(tree.root, sum)) {
            Console.WriteLine("There is a root to leaf "
                              + "path with sum " + sum);
        }
        else {
            Console.WriteLine("There is no root to leaf "
                              + "path with sum " + sum);
        }
    }
}
 
// This code is contributed by Shrikant13

chevron_right


Output



There is a root-to-leaf path with sum 21

Time Complexity: O(n)
References: http://cslibrary.stanford.edu/110/BinaryTrees.html
Author: Tushar Roy

https://www.youtube.com/watch?v=4TcWoBQmG4c 
 

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up