# 112. Path Sum

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.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

# Solution

Approach 1: BFS/DFS iteration.

# Code (Python)

Approach 1:

class Solution:
    def hasPathSum(self, root, sum):
        if not root:
            return False
        stack = [(root, root.val)]
        while stack:
            node, sum_so_far = stack.pop()
            if not node.left and not node.right and sum_so_far == sum:
                return True
            if node.left:
                stack.append((node.left, sum_so_far + node.left.val))
            if node.right:
                stack.append((node.right, sum_so_far + node.right.val))
        return False

# Code (C++)

Approach 1:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if (root == NULL) return false;
        queue<pair<TreeNode*,int>> nodeQueue;
        nodeQueue.push(pair<TreeNode*,int>(root, sum));
        while (!nodeQueue.empty())
        {
            TreeNode *node = nodeQueue.front().first;
            int sumRemains = nodeQueue.front().second;
            nodeQueue.pop();
            if (node->left == NULL && node->right == NULL && node->val == sumRemains)
                return true;
            if (node->left)
                nodeQueue.push(pair<TreeNode*,int>(node->left, sumRemains - node->val));
            if (node->right)
                nodeQueue.push(pair<TreeNode*,int>(node->right, sumRemains - node->val));
        }
        return false;
    }
};