# LeetCode Path Sum

177人阅读 评论(0)

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：62102次
• 积分：3257
• 等级：
• 排名：第10440名
• 原创：288篇
• 转载：0篇
• 译文：0篇
• 评论：4条
文章分类
阅读排行
最新评论