# 112. Path Sum

### Description

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.

**Note:** A leaf is a node with no children.

### Constraints

### Approach

### Links

* [GeeksforGeeks](https://www.geeksforgeeks.org/root-to-leaf-path-sum-equal-to-a-given-number/)
* [Leetcode](https://leetcode.com/problems/path-sum/)
* [ProgramCreek](https://www.programcreek.com/2013/01/leetcode-path-sum/)
* YouTube

### **Examples**

{% tabs %}
{% tab title="Example 1" %}
**Input:**

tree=\[5,4,8,11,null,13,4,7,2,null,null,null,1]

sum=22

**Output:** true

**Explanation:**

<div align="left"><img src="/files/-MFzUEGTxISnoqihIfUx" alt=""></div>
{% endtab %}
{% endtabs %}

### **Solutions**

{% tabs %}
{% tab title="TreeNode" %}

```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;
    }
}
```

{% endtab %}

{% tab title="Solution 1" %}

```java
/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return false;
        
        sum -= root.val;
        if(root.left == null && root.right == null) {
            return sum == 0;
        }
        
        return hasPathSum(root.left, sum) || 
                hasPathSum(root.right, sum);
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

* Print Palindromic Paths of Binary tree - [GFG](https://www.geeksforgeeks.org/print-palindromic-paths-of-binary-tree/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://code-snippets.hbamithkumara.com/leetcode/problems/101-200/path-sum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
