-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode00hasPathSum.java
More file actions
56 lines (50 loc) · 1.73 KB
/
code00hasPathSum.java
File metadata and controls
56 lines (50 loc) · 1.73 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
45
46
47
48
49
50
51
52
53
54
55
56
package com.leecode.tree;
public class code00hasPathSum {
code00hasPathSum left;
code00hasPathSum right;
int val;
//取值函数
code00hasPathSum(int val) {
this.val = val;
}
public static void main(String[] args) {
code00hasPathSum root = new code00hasPathSum(5);
code00hasPathSum left1 = new code00hasPathSum(4);
code00hasPathSum left2 = new code00hasPathSum(11);
code00hasPathSum left3 = new code00hasPathSum(7);
code00hasPathSum left4 = new code00hasPathSum(2);
code00hasPathSum right1 = new code00hasPathSum(8);
code00hasPathSum right2 = new code00hasPathSum(13);
code00hasPathSum right3 = new code00hasPathSum(4);
code00hasPathSum right4 = new code00hasPathSum(1);
// 构建这棵树
root.left = left1;
left1.left = left2;
left2.left = left3;
left2.right = left4;
root.right = right1;
right1.left = right2;
right1.right = right3;
right3.right = right4;
// 传入根节点
int sum = 22;
boolean res = hasPathSum(root, sum);
if (res) {
System.out.printf("这棵树有和为%d的路径", sum);
} else {
System.out.printf("这棵树没有和为%d的路径", sum);
}
}
// 路径之和方法
public static boolean hasPathSum(code00hasPathSum root, int sum) {
if (root == null) {
return false;
}
sum -= root.val;
if (root.left == null && root.right == null) {
return (sum == 0);
}
// 开始递归
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
}
}