Root to leaf path sum equal to a given number in BST
Given a BST and a number. The task is to check whether the given number 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.
Approach: The idea is to traverse from root to all leaves in top-down fashion maintaining a path array to store current root to leaf path. While traversing, store data of all nodes of current path in the array path. Whenever a leaf node is reached, calculate the sum of all of the nodes on the current path using the array path and check if it is equal to the given sum.
Below is the implementation of above approach:
- Time complexity: O(n) where n is no of nodes in given BST
- Auxiliary Space: O(n)
My Personal Notes arrow_drop_up
Please Login to comment...