Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
LeetCode-112: Given the root
of a binary tree and an integer targetSum
, return true
if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum
.
A leaf is a node with no children.
We can use a recursive DFS algorithm to traverse the tree with a base case of null
node:
null
- return false
.targetSum
- return true
.targetSum
as targetSum - root.val
.Here is a java implementation of the DFS approach:
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
// leaf node and sum of path from root to
// this leaf node is equal to targetSum
if (root.left == null &&
root.right == null &&
targetSum == root.val) {
return true;
}
// recursively check left and right subtree
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
The time complexity for the above approach is $O(N)$ where $N$ is the number of nodes in the binary tree. The space complexity is $O(H)$ where $H$ is the height of the binary tree which is the space used by the recursion stack.
Be notified of new posts. Subscribe to the RSS feed.