Path Sum (Binary Tree Root to Leaf Path Sum)

Binary Tree Root to Leaf Path Sum Equal to a Given Number.

Given a binary tree and a sum, Determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

If path is found then return true else return false.

Note: What is leaf node? Any node whose left and right children is null is known as leaf node.

For example –

In this Binary tree, there exist a path from root-to-leaf node whose sum is equal to the given sum (which is 16).

Now, suppose if the given value of sum is 12. Then in this case we simply return false. As the root-to-leaf node path does not exist in a Binary tree whose sum is equal to 12.

We have discussed the problem statement, before seeing the solution. Let’s think how we can solve this problem efficiently.

There are multiple approaches we can use to solve this problem. We can either use iterative or recursive approach to solve this problem. In this tutorial, i am going to discuss only recursive solution.

Recursion vs Iteration

Programming Video Tutorials

Also, i have added the video tutorial at the end of this post.

Path Sum (Binary Tree Root to Leaf Path Sum Equal to a Given Number) – Java Code

To find the valid path, we have to traverse this binary tree recursively. We first traverse the left half of the binary tree. If we found the path then we return true. Else, we traverse right half of the binary tree.

If we found the path in any half of the tree we return true else we return false.

The time complexity of this approach is O(n).

In this video tutorial, I have explained the recursive implementation of a solution.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.