-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode112.java
More file actions
44 lines (40 loc) · 1.46 KB
/
LeetCode112.java
File metadata and controls
44 lines (40 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import util.TreeNode;
public class LeetCode112 {
public static void main(String[] args) {
// 输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
// 输出:true
System.out.println(new Solution112().hasPathSum(
TreeNode.buildTree(new Integer[] { 5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1 }), 22));
// 输入:root = [1,2,3], targetSum = 5
// 输出:false
System.out.println(new Solution112().hasPathSum(
TreeNode.buildTree(new Integer[] { 1, 2, 3 }), 5));
// 输入:root = [], targetSum = 0
// 输出:false
System.out.println(new Solution112().hasPathSum(
TreeNode.buildTree(new Integer[] {}), 0));
}
}
class Solution112 {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
// 说明此时root是叶子结点
if (targetSum == root.val) {
// 叶子结点与需要的targetNum一致
return true;
} else {
return false;
}
}
targetSum -= root.val;
if ((root.left != null && hasPathSum(root.left, targetSum))
|| (root.right != null && hasPathSum(root.right, targetSum))) {
return true;
} else {
return false;
}
}
}