Problem Description
Given a binary tree and a value sum, judge whether there is a path from the root node to the leaf node that the sum of the node values is equal to the sum.
Enter description:
Enter a tree
Output description:
output whether there is a path to the specified sum
Example
Example 1
Enter
22
Output (path included: 5->4->11->2)
true
Solutions
analysis
- Judge all paths recursively, as long as it contains return true, the relationship between different paths is ||.
method
- Recursively determine whether the path of the specified sum is included
Code
// 思路1
public class Solution {
public boolean hasPathSum (TreeNode root, int sum) {
// write code here
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return (sum - root.val == 0);
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
If you want to test, you can go directly to the link of Niuke.com to do the test