VOOZH about

URL: https://www.geeksforgeeks.org/dsa/root-to-leaf-path-sum-equal-to-a-given-number-in-bst/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 11 Jul, 2025

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.


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.

Comment