Open In App

Root to leaf path sum equal to a given number in BST

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Search Tree and a sum target. The task is to check whether the given sum is equal to the sum of all the node from root leaf across any of the root to leaf paths in the given Binary Search Tree.

Examples:

Input:

Root-to-leaf-path-sum-equal-to-a-given-number-in-BST-2

Output: true
Explanation: root-to-leaf path [1, 3, 4] sums up to the target value 8.

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


Input:

Root-to-leaf-path-sum-equal-to-a-given-number-in-BST-3


Output: false
Explanation: There is no root-to-leaf path that sums up to the target value 9.

Approach:

The idea is to recursively traverse the binary tree, accumulating the sum of node values along the path. At each node, we check if we have reached a leaf node and if the accumulated sum matches the target. If the sum matches at any leaf node, we return true. If not, we continue checking both the left and right subtrees until we either find a valid path or exhaust the tree.

C++
// C++ program to check if a root-to-leaf path exists 
// with the given sum in a Binary Search Tree
#include <bits/stdc++.h>
using namespace std;

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

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

// Function to check if a root-to-leaf path has 
// the target sum
bool hasPathSum(Node* curr, int target, int currsum) {
    if (curr == nullptr) {
        return false;
    }

    // Add current node's value to the running sum
    currsum += curr->data;

    // Check if it's a leaf node and the sum equals 
    // the target
    if (curr->left == nullptr && curr->right == nullptr) {
        return currsum == target;
    }

    // Recursively check left and right subtrees
    return hasPathSum(curr->left, target, currsum) || 
           hasPathSum(curr->right, target, currsum);
}

// Wrapper function to start the check from root
bool checkPathSum(Node* root, int target) {
    return hasPathSum(root, target, 0);
}

int main() {
  
    // Representation of given Binary Search Tree
    //        1
    //       / \
    //      9   3
    //         / \
    //        4   7
    Node* root = new Node(1);
    root->left = new Node(9);
    root->right = new Node(3);
    root->right->left = new Node(4);
    root->right->right = new Node(7);

    int target = 8;

    if (checkPathSum(root, target)) {
        cout << "true" << endl;
    } 
    else {
        cout << "false" << endl;
    }

    return 0;
}
Java
// Java program to check if a root-to-leaf path exists 
// with the given sum in a Binary Search Tree
import java.util.*;

class Node {
    int data;
    Node left, right;

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

class GfG {

    // Utility function to check root-to-leaf path sum
    static boolean hasPathSum(Node curr, 
                             int target, int currsum) {
        if (curr == null) {
            return false;
        }

        // Add current node's value to the running sum
        currsum += curr.data;

        // Check if it's a leaf node and the sum equals target
        if (curr.left == null && curr.right == null) {
            return currsum == target;
        }

        // Recursively check left and right subtrees
        return hasPathSum(curr.left, target, currsum) || 
               hasPathSum(curr.right, target, currsum);
    }

    // Wrapper function to start the check from root
    static boolean checkPathSum(Node root, int target) {
        return hasPathSum(root, target, 0);
    }

    public static void main(String[] args) {
      
        // Representation of given Binary Search Tree
        //        1
        //       / \
        //      9   3
        //         / \
        //        4   7
        Node root = new Node(1);
        root.left = new Node(9);
        root.right = new Node(3);
        root.right.left = new Node(4);
        root.right.right = new Node(7);

        int target = 8;

        if (checkPathSum(root, target)) {
            System.out.println("true");
        } 
        else {
            System.out.println("false");
        }
    }
}
Python
# Python program to check if a root-to-leaf path 
# exists with the given sum in a Binary Tree
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Function to check root-to-leaf path sum
def hasPathSum(curr, targetSum, currSum):
    if curr is None:
        return False

    # Add current node's value to the running sum
    currSum += curr.data

    # Check if it's a leaf node and the sum equals target
    if curr.left is None and curr.right is None:
        return currSum == targetSum

    # Recursively check left and right subtrees
    return (hasPathSum(curr.left, targetSum, currSum) or 
            hasPathSum(curr.right, targetSum, currSum))

# Wrapper function to start the check from root
def checkPathSum(root, targetSum):
    return hasPathSum(root, targetSum, 0)

if __name__ == '__main__':

    # Representation of the binary tree
    #        1
    #       / \
    #      9   3
    #         / \
    #        4   7
    root = Node(1)
    root.left = Node(9)
    root.right = Node(3)
    root.right.left = Node(4)
    root.right.right = Node(7)

    targetSum = 8

    if checkPathSum(root, targetSum):
        print("true")
    else:
        print("false")
C#
// C# program to check if a root-to-leaf path
// exists with the given sum in a Binary Tree
using System;

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

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

class GfG {

    // Function to check root-to-leaf path sum
    static bool HasPathSum(Node curr, int target,
                                     int currSum) {
        if (curr == null) {
            return false;
        }

        // Add current node's value to the running sum
        currSum += curr.data;

        // Check if it's a leaf node and sum matches target
        if (curr.left == null && curr.right == null) {
            return currSum == target;
        }

        // Recursively check left and right subtrees
        return HasPathSum(curr.left, target, currSum) || 
               HasPathSum(curr.right, target, currSum);
    }

    // Wrapper function to start from root
    static bool CheckPathSum(Node root, int target) {
        return HasPathSum(root, target, 0);
    }

    static void Main(string[] args) {

        // Representation of given Binary Tree
        //        1
        //       / \
        //      9   3
        //         / \
        //        4   7
        Node root = new Node(1);
        root.left = new Node(9);
        root.right = new Node(3);
        root.right.left = new Node(4);
        root.right.right = new Node(7);

        int target = 7;

        if (CheckPathSum(root, target)) {
            Console.WriteLine("true");
        } 
        else {
            Console.WriteLine("false");
        }
    }
}
JavaScript
// JavaScript program to check if a root-to-leaf
// path exists with the given sum in a Binary Tree
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Function to check root-to-leaf path sum
function hasPathSum(curr, target, currSum) {
    if (curr === null) {
        return false;
    }

    // Add current node's value to the running sum
    currSum += curr.data;

    // Check if it's a leaf node and sum matches target
    if (curr.left === null && curr.right === null) {
        return currSum === target;
    }

    // Recursively check left and right subtrees
    return hasPathSum(curr.left, target, currSum) || 
           hasPathSum(curr.right, target, currSum);
}

// Wrapper function to start from root
function checkPathSum(root, target) {
    return hasPathSum(root, target, 0);
}

// Representation of given Binary Tree
//        1
//       / \
//      9   3
//         / \
//        4   7
const root = new Node(1);
root.left = new Node(9);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(7);

const target = 8;

if (checkPathSum(root, target)) {
    console.log("true");
}
else {
    console.log("false");
}

Output
true

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


Similar Reads