-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathPathSum.java
More file actions
69 lines (59 loc) · 1.72 KB
/
PathSum.java
File metadata and controls
69 lines (59 loc) · 1.72 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
57
58
59
60
61
62
63
64
65
66
67
package depthfirstsearch;
// Source : https://leetcode.com/problems/path-sum/
// Id : 112
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2020-01-01
// Topic : Depth-First Search
// Level : Easy
// Other :
// Tips :
// Result : 100.00% 6.52%
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
public class PathSum {
// 100.00% 0ms 6.52%
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
if (root.left == null && root.right == null) {
return root.val == sum;
}
if (hasPathSum(root.left, sum - root.val))
return true;
if (hasPathSum(root.right, sum - root.val))
return true;
return false;
}
public boolean hasPathSumIteration(TreeNode root, int sum) {
// public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
// "a root-to-leaf path "
if (node.val == sum && node.left == null && node.right == null)
return true;
if (node.left != null) {
node.left.val += node.val;
queue.add(node.left);
}
if (node.right != null) {
node.right.val += node.val;
queue.add(node.right);
}
}
return false;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}