https://github.com/emahtab/path-sum
https://github.com/emahtab/path-sum
dfs leetcode tree
Last synced: about 1 month ago
JSON representation
- Host: GitHub
- URL: https://github.com/emahtab/path-sum
- Owner: eMahtab
- Created: 2021-08-21T00:59:11.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2021-08-21T01:04:06.000Z (about 4 years ago)
- Last Synced: 2025-03-28T01:30:10.768Z (8 months ago)
- Topics: dfs, leetcode, tree
- Homepage:
- Size: 21.5 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Path Sum
## https://leetcode.com/problems/path-sum
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.

# Implementation : DFS
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null)
return false;
return traverse(root, targetSum);
}
private boolean traverse(TreeNode node, int targetSum) {
if(node.left == null && node.right == null && node.val == targetSum)
return true;
boolean leftPath = false;
if(node.left != null)
leftPath = traverse(node.left, targetSum - node.val);
boolean rightPath = false;
if(node.right != null)
rightPath = traverse(node.right, targetSum - node.val);
return leftPath || rightPath;
}
}
```