# 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 Path Sum 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)