###### LeetCode 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.

For 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:

import java.util.*;

public class Solution {
int targetSum;

public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
this.targetSum = sum;
return dfs(root, 0);
}

boolean dfs(TreeNode root, int tempSum) {
tempSum += root.val;
if (root.left == null && root.right == null) {
if (tempSum == targetSum)
return true;
return false;
}
boolean flag = false;
if (root.left != null)
flag = flag | dfs(root.left, tempSum);
if (root.right != null)
flag = flag | dfs(root.right, tempSum);
return flag;
}
}

#### Leetcode 437. Path Sum III 路径和3 解题报告

2016-10-23 14:29:28

#### Path Sum II -- LeetCode

2014-04-14 23:59:49

#### LeetCode || Minimum Path Sum

2014-10-19 11:40:15

#### 【leetcode c++】113 Path Sum II

2015-08-01 00:06:17

#### [python]leetcode(437). Path Sum III

2017-09-15 09:55:43

#### LeetCode 112 — Path Sum（C++ Java Python）

2014-04-03 16:01:19

#### 【LeetCode】113. Path Sum II 基于Java和C++的解法及分析

2016-05-09 22:25:36

#### LeetCode 124: Binary Tree Maximum Path Sum 树形动态规划

2015-09-02 15:52:14

#### 【LeetCode-面试算法经典-Java实现】【113-Path Sum II（路径和）】

2015-08-12 06:23:36

#### [C++]LeetCode: 90 Path Sum

2015-01-12 15:01:13

## 不良信息举报

LeetCode Path Sum