Open In App

Root to leaf path sum equal to a given number

Last Updated : 04 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Input:

Root-to-leaf-path-sum-equal-to-a-given-number

Output: True 
Explanation:  Root to leaf path sum, existing in this tree are:

  • 10 -> 8 -> 3  = 21
  • 10 -> 8 -> 5  = 23
  • 10 -> 2 -> 2 = 14

So it is possible to get sum = 21

[Expected Approach - 1] Using Recursion - O(n) Time and O(h) Space

The idea is to recursively move to left and right subtree and decrease sum by the value of the current node and if at any point the current node is equal to a leaf node and remaining sum is equal to zero then the answer is true.

Follow the given steps to solve the problem using the above approach:

  • Recursively move to the left and right subtree and at each call decrease the sum by the value of the current node.
  • If at any level the current node is a leaf node and the remaining sum is equal to zero then return true.

Below is the implementation of the above approach:

C++
// C++ Program to Check if Root to leaf path
// sum equal to a given number

#include <bits/stdc++.h>

using namespace std;

class Node {
public:
    Node *left, *right;
    int data;

    Node(int key) {
        data = key;
        left = nullptr;
        right = nullptr;
    }
};

// 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.
bool hasPathSum(Node* root, int sum) {
    if (root == NULL)
        return 0;

    int subSum = sum - root->data;

    // If we reach a leaf node and sum becomes 0 then return true
    if (subSum == 0 && root->left == nullptr && root->right == nullptr)
        return 1;

    // Otherwise check both subtrees
    bool left = 0, right = 0;
    
    if (root->left)
        left = hasPathSum(root->left, subSum);
    if (root->right)
        right = hasPathSum(root->right, subSum);

    return left || right;
}

int main() {
  
    int sum = 21;

    // Constructed binary tree is
    //         10
    //       /    \
    //      8      2
    //     / \    /
    //    3   5  2
  
    Node* root = new Node(10);
    root->left = new Node(8);
    root->right = new Node(2);
    root->left->left = new Node(3);
    root->left->right = new Node(5);
    root->right->left = new Node(2);
  
    if(hasPathSum(root, sum)) {
      cout << "True"<< endl;
    }
  	else cout << "False";

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};



// Function to check if there is a root-to-leaf 
// path with a given sum
int hasPathSum(struct Node* root, int sum) {
    if (root == NULL) {
        return sum == 0;
    }

    int subSum = sum - root->data;

    // If we reach a leaf node and sum becomes
  	// 0 then return true
    if (subSum == 0 && root->left == NULL 
        && root->right == NULL) {
        return 1;
    }

    // Otherwise check both subtrees
    return hasPathSum(root->left, subSum) 
      || hasPathSum(root->right, subSum);
}

struct Node* createNode(int key) {
    struct Node* node = (
      struct Node*)malloc(sizeof(struct Node));
    node->data = key;
    node->left = NULL;
    node->right = NULL;
    return node;
}

int main() {
  
    // Constructed binary tree is
    //         10
    //       /    \
    //      8      2
    //     / \    /
    //    3   5  2
  
    int sum = 21;
  
    struct Node* root = createNode(10);
    root->left = createNode(8);
    root->right = createNode(2);
    root->left->left = createNode(3);
    root->left->right = createNode(5);
    root->right->left = createNode(2);

    if (hasPathSum(root, sum)) {
        printf("True\n");
    } else {
        printf("False\n");
    }
  
    return 0;
}
Java
// Java Program to Check if Root to leaf path 
// sum equal to a given number

class Node {
    Node left, right;
    int data;

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

class GfG {
  
    // 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.
    static boolean hasPathSum(Node root, int sum) {
        if (root == null) return false;

        int subSum = sum - root.data;

        // If we reach a leaf node and sum becomes 0 then return true
        if (subSum == 0 && root.left == null 
            && root.right == null) return true;

        // Otherwise check both subtrees
        boolean left = false, right = false;

        if (root.left != null) left = hasPathSum(root.left, subSum);
        if (root.right != null) right = hasPathSum(root.right, subSum);

        return left || right;
    }

    public static void main(String[] args) {
        int sum = 21;

        // Constructed binary tree is
        //         10
        //       /    \
        //      8      2
        //     / \    /
        //    3   5  2

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

        System.out.println(hasPathSum(root, sum));
    }
}
Python
# Python Program to Check if Root to leaf path
# sum equal to a given number

class 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.
def hasPathSum(root, sum):
    if root is None:
        return False

    subSum = sum - root.data

    # If we reach a leaf node and sum becomes 0 then return true
    if subSum == 0 and root.left is None and root.right is None:
        return True

    # Otherwise check both subtrees
    left = hasPathSum(root.left, subSum) if root.left else False
    right = hasPathSum(root.right, subSum) if root.right else False

    return left or right

if __name__ == "__main__":
    sum = 21

    # Constructed binary tree is
    #         10
    #       /    \
    #      8      2
    #     / \    /
    #    3   5  2

    root = Node(10)
    root.left = Node(8)
    root.right = Node(2)
    root.left.left = Node(3)
    root.left.right = Node(5)
    root.right.left = Node(2)

    print(hasPathSum(root, sum))
C#
// C# Program to Check if Root to leaf path
// sum equal to a given number 

using System;

class Node {
    public Node left, right;
    public int data;

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

class GfG {
  
    // 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.
    static bool HasPathSum(Node root, int sum) {
        if (root == null) return false;

        int subSum = sum - root.data;

        // If we reach a leaf node and sum becomes 0 then return true
        if (subSum == 0 && root.left == null 
            && root.right == null) return true;

        // Otherwise check both subtrees
        bool left = false, right = false;

        if (root.left != null) left = HasPathSum(root.left, subSum);
        if (root.right != null) right = HasPathSum(root.right, subSum);

        return left || right;
    }

    static void Main(string[] args) {
        int sum = 21;

        // Constructed binary tree is
        //         10
        //       /    \
        //      8      2
        //     / \    /
        //    3   5  2

        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);
      
        Console.WriteLine(HasPathSum(root, sum));
    }
}
JavaScript
// JavaScript Program to Check if Root to leaf
// path sum equal to a given number

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

// 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.
function hasPathSum(root, sum) {
    if (root === null) return false;

    const subSum = sum - root.data;

    // If we reach a leaf node and sum becomes 0 then return true
    if (subSum === 0 && root.left === null 
    	&& root.right === null) return true;

    // Otherwise check both subtrees
    const left = root.left ? hasPathSum(root.left, subSum) : false;
    const right = root.right ? hasPathSum(root.right, subSum) : false;

    return left || right;
}

// Constructed binary tree is
//         10
//       /    \
//      8      2
//     / \    /
//    3   5  2

const sum = 21;
const root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);

console.log(hasPathSum(root, sum));

Output
True

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

[Expected Approach - 2] Using Iterative - O(n) Time and O(h) Space

In this approach, we use a stack to perform a preorder traversal of the binary tree. We maintain two stacks - one to store the nodes and another to store the sum of values along the path to that node. Whenever we encounter a leaf node, we check if the sum matches the target sum. If it does, we return true, otherwise, we continue traversing the tree.

Follow the given steps to solve the problem using the above approach:

  • Check if the root node is NULL. If it is, return false, since there is no path to follow.
  • Create two stacks, one for the nodes and one for the sums. Push the root node onto the node stack and its data onto the sum stack. While the node stack is not empty, do the following:
    • Pop a node from the node stack and its corresponding sum from the sum stack.
    • Check if the node is a leaf node (i.e., it has no left or right child). If it is, check if the sum equals the target sum. If it does, return true, since we have found a path that adds up to the target sum.
    • If the node has a left child, push it onto the node stack and push the sum plus the left child’s data onto the sum stack.
    • If the node has a right child, push it onto the node stack and push the sum plus the right child’s data onto the sum stack.
  • If we reach this point, it means we have exhausted all paths and haven’t found any that add up to the target sum. Return false.

Below is the implementation of the above approach:

C++
// C++ Program to Check if Root to leaf path sum 
// equal to a given number

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    Node *left, *right;
    int data;

    Node(int key) {
        data = key;
        left = nullptr;
        right = nullptr;
    }
};

// Check if there's a root-to-leaf path with the given sum
bool hasPathSum(Node* root, int targetSum) {
    if (root == nullptr) return false;
    
    stack<Node*> stk;
    stack<int> sums;
    stk.push(root);
    sums.push(root->data); 
    
    while (!stk.empty()) {
        Node* node = stk.top(); 
      	stk.pop();
        int sum = sums.top(); 
      	sums.pop();
        
        // Check if leaf node and sum matches
        if (node->left == nullptr && node->right == nullptr
            && sum == targetSum)
            return true;
        
        // Add children to stacks with updated sums
        if (node->left) {
            stk.push(node->left);
            sums.push(sum + node->left->data); 
        }
        if (node->right) {
            stk.push(node->right);
            sums.push(sum + node->right->data); 
        }
    }
    
    return false;
}

int main() {
  
      // Construct binary tree
      //         10
      //       /  \
      //      8    2
      //     / \   /
      //    3   5 2
  
    Node* root = new Node(10);
    root->left = new Node(8);
    root->right = new Node(2);
    root->left->left = new Node(3);
    root->left->right = new Node(5);
    root->right->left = new Node(2);
   
    int targetSum = 21;
  	 if(hasPathSum(root, targetSum)) {
      	cout << "True"<< endl;
    }
  	else cout << "False";
    
    return 0;
}
Java
// Java Program to Check if Root to leaf path 
// sum equal to a given number 

import java.util.Stack; 

class Node {
    Node left, right;
    int data;

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

class GfG {
  
    // Check if there's a root-to-leaf path with the given sum
    static boolean hasPathSum(Node root, int targetSum) {
        if (root == null) return false;

        Stack<Node> stk = new Stack<>(); 
        Stack<Integer> sums = new Stack<>(); 
        stk.push(root);
        sums.push(root.data);

        while (!stk.isEmpty()) {
            Node node = stk.pop();
            int sum = sums.pop();

            // Check if leaf node and sum matches
            if (node.left == null && node.right == null 
                && sum == targetSum)
                return true;

            // Add children to stacks with updated sums
            if (node.left != null) {
                stk.push(node.left);
                sums.push(sum + node.left.data);
            }
            if (node.right != null) {
                stk.push(node.right);
                sums.push(sum + node.right.data);
            }
        }

        return false;
    }

    public static void main(String[] args) {
      
         // Construct binary tree
        //         10
        //       /  \
        //      8    2
        //     / \   /
        //    3   5 2
        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);

        int targetSum = 21;
        System.out.println(hasPathSum(root, targetSum));
    }
}
Python
# Python Program to Check if Root to leaf path 
# sum equal to a given number 

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

# Check if there's a root-to-leaf path with
# the given sum
def hasPathSum(root, targetSum):
    if root is None:
        return False
    
    stack = []
    sums = []
    stack.append(root)
    sums.append(root.data)
    
    while stack:
        node = stack.pop()
        sumValue = sums.pop()
        
        # Check if leaf node and sum matches
        if node.left is None and node.right is None \
        and sumValue == targetSum:
            return True
        
        # Add children to stacks with updated sums
        if node.left:
            stack.append(node.left)
            sums.append(sumValue + node.left.data)
        if node.right:
            stack.append(node.right)
            sums.append(sumValue + node.right.data)
    
    return False

if __name__ == "__main__":
  
    # Construct binary tree
    #         10
    #       /  \
    #      8    2
    #     / \   /
    #    3   5 2
    
    root = Node(10)
    root.left = Node(8)
    root.right = Node(2)
    root.left.left = Node(3)
    root.left.right = Node(5)
    root.right.left = Node(2)
   
    targetSum = 21
    
    print(hasPathSum(root, targetSum))
C#
// C# Program to Check if Root to leaf path
// sum equal to a given number 

using System;
using System.Collections.Generic;

class Node {
    public Node left, right;
    public int data;

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

class GfG {
  
    // Check if there's a root-to-leaf path with the given sum
    static bool hasPathSum(Node root, int targetSum) {
        if (root == null) return false;

        Stack<Node> stk = new Stack<Node>();
        Stack<int> sums = new Stack<int>();
        stk.Push(root);
        sums.Push(root.data);

        while (stk.Count > 0) {
            Node node = stk.Pop();
            int sum = sums.Pop();

            // Check if leaf node and sum matches
            if (node.left == null && node.right == null
                && sum == targetSum)
                return true;

            // Add children to stacks with updated sums
            if (node.left != null) {
                stk.Push(node.left);
                sums.Push(sum + node.left.data);
            }
            if (node.right != null) {
                stk.Push(node.right);
                sums.Push(sum + node.right.data);
            }
        }

        return false;
    }

    static void Main(string[] args) {
      
        // Construct binary tree
        //         10
        //       /  \
        //      8    2
        //     / \   /
        //    3   5 2
      
        Node root = new Node(10);
        root.left = new Node(8);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.left = new Node(2);

        int targetSum = 21;
        Console.WriteLine(hasPathSum(root, targetSum));
    }
}
JavaScript
// JavaScript Program to Check if Root to leaf
// path sum equal to a given number 

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

// Check if there's a root-to-leaf path 
// with the given sum
function hasPathSum(root, targetSum) {
    if (root === null) return false;

    const stack = [];
    const sums = [];
    stack.push(root);
    sums.push(root.data);
    
    while (stack.length > 0) {
        const node = stack.pop();
        const sum = sums.pop();
        
        // Check if leaf node and sum matches
        if (node.left === null && node.right === null 
        	&& sum === targetSum)
            return true;
        
        // Add children to stacks with updated sums
        if (node.left) {
            stack.push(node.left);
            sums.push(sum + node.left.data);
        }
        if (node.right) {
            stack.push(node.right);
            sums.push(sum + node.right.data);
        }
    }
    
    return false;
}

  // Construct binary tree
  //         10
  //       /  \
  //      8    2
  //     / \   /
  //    3   5 2
const root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);

const targetSum = 21;
console.log(hasPathSum(root, targetSum));

Output
True

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


Next Article

Similar Reads