-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwoSum4.java
More file actions
73 lines (59 loc) · 1.93 KB
/
TwoSum4.java
File metadata and controls
73 lines (59 loc) · 1.93 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
68
69
70
71
72
73
package binary_search_tree;
import java.util.*;
/**
* Description: https://leetcode.com/problems/two-sum-iv-input-is-a-bst
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class TwoSum4 {
public boolean findTargetViaInorderTraversal(TreeNode root, int k) {
List<Integer> inorder = inorderTraversal(root); // inorder traversal of a BST is a sorted array
return isTargetExist(inorder, k);
}
private List<Integer> inorderTraversal(TreeNode root) {
List<Integer> inorder = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
inorder.add(root.val);
root = root.right;
}
}
return inorder;
}
private boolean isTargetExist(List<Integer> inorder, int target) {
int left = 0;
int right = inorder.size() - 1;
while (left < right) {
int sum = inorder.get(left) + inorder.get(right);
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
return true;
}
}
return false;
}
public boolean findTargetViaRecursion(TreeNode root, int k) {
return isTargetExist(root, k, new HashSet<>());
}
private boolean isTargetExist(TreeNode root, int target, Set<Integer> seen) {
if (root == null) return false;
if (seen.contains(target - root.val)) return true;
seen.add(root.val);
return isTargetExist(root.left, target, seen)
|| isTargetExist(root.right, target, seen);
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
}