12(July) Root to leaf path sum
12. Root to Leaf Path Sum
The problem can be found at the following link: Question Link
Problem Description
Given a binary tree and an integer target, check whether there is a root-to-leaf path with its sum equal to the target.
Examples:
Input:
tree = [1, 2, 3]
target = 2Output:
falseExplanation: There is no root to leaf path with sum 2.
My Approach
Base Case:
If the
nodeisNone, returnfalse.
Target Adjustment:
Subtract the value of the current
nodefrom thetarget.
Leaf Node Check:
If the current
nodeis a leaf (i.e., it has no left or right child), check if the adjustedtargetis zero.
Recursive Call:
Recursively check the left and right subtrees to see if any path matches the target sum.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we need to visit each node once in the worst case.
Expected Auxiliary Space Complexity: O(h), where
his the height of the tree. This is due to the recursive call stack.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated