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.
题意:从二叉树的根节点到叶子节点的所有路径中,有没有一条路径的和等于给定的sum。
思路:
用深度搜索的方法,遍历出二叉树的所有路径。
在路径上搜索当前节点的下一个节点时,将sum减去当前节点的val。
如果一个节点左右节点都是null,则这个节点是叶子节点,即完成了一条路径的搜索,如果此时这个叶子节点的val和当前传参sum相等,那么就找到了要求的路径。
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
return dfs(root, sum);
}
public boolean dfs(TreeNode root, int sum) {
//一个path走到了叶子节点,如果节点val和sum相等,这个path就满足条件
if (root.left == null && root.right == null) {
return root.val == sum ? true : false;
}
//左子树中找到了这样的path
if (root.left != null && dfs(root.left, sum - root.val)) {
return true;
}
//右子树中找到了这样的path
if (root.right != null && dfs(root.right, sum - root.val)) {
return true;
}
//左右子树都没有这样的path,返回false
return false;
}