-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
38 lines (29 loc) · 1.02 KB
/
PathSum.java
File metadata and controls
38 lines (29 loc) · 1.02 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
package com.mirraico.leetcode;
public class PathSum {
public boolean hasPathSum(TreeNode root, int sum) {
return dfs(root, 0, sum);
}
public boolean dfs(TreeNode root, int tempAns, int sum) {
if (null == root) return false;
tempAns += root.val;
if (null == root.left && null == root.right) {
return tempAns == sum;
}
if (dfs(root.left, tempAns, sum) || dfs(root.right, tempAns, sum)) {
return true;
}
return false;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(8);
root.left.left = new TreeNode(11);
root.right.left = new TreeNode(13);
root.right.right = new TreeNode(4);
root.left.left.left = new TreeNode(7);
root.left.left.right = new TreeNode(2);
root.right.right.right = new TreeNode(1);
System.out.println(new Solution().hasPathSum(root, 22));
}
}