题目意思是给了一个二叉树,每个节点对应一个值,同时给了一个指定的树。
然后请问是否有一条从根节点开始,到叶节点的路径,其和正好等于那个值。
做法就是简单的DFS,如果到了叶节点刚好等于那个值就返回True,如果不够或者超过则返回False(搜索的时候如果还没到叶节点就超了,就回溯回去)。
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.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/**
* 直接dfs就好了。。。就是注意下区分根节点和叶节点的定义,我当时都被坑了
*
* 叶节点是左右都没有孩子。。我一开始被坑了。。
*/
public class Solution {
public boolean dfs(TreeNode root,int sum){
if(root==null)
return false;
sum-=root.val;
if(root.left==null && root.right==null)
return sum==0;
return dfs(root.left,sum) || dfs(root.right,sum);
}
public boolean hasPathSum(TreeNode root, int sum) {
return dfs(root,sum);
}
}