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.
解题思路
通过dfs检验每次路径相加之和, 搜索到下一层保存当前的值,直到二叉树的叶子结点,当前累加的值和目标的sum相同的话返回true
解题代码
package leetcode;
/**
* @author zqynn
* 本题大意 给定一颗二叉树,每科二叉树都有给定的权值,
* 如果二叉树上的全值能够组成一个特定的数那么久返回 true 否则就返回false
**/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return PathSum(root, 0, sum);
}
public boolean PathSum(TreeNode root, int cur, int sum){
if(root == null) return false;
cur += root.val;
if(root.left == null && root.right == null){
return cur == sum;
}
return PathSum(root.left, cur, sum) || PathSum(root.right, cur, sum);
}
}