Skip to content

Commit bf870c2

Browse files
author
Li Li
committed
add code for 653.
1 parent 9505e5a commit bf870c2

File tree

3 files changed

+78
-1
lines changed

3 files changed

+78
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// HashSet + recursion traverse
2+
public class Solution {
3+
HashSet<int> set = new HashSet<int>();
4+
public bool FindTarget(TreeNode root, int k) {
5+
if (root == null) {
6+
return false;
7+
}
8+
if (set.Contains(k - root.val)) {
9+
return true;
10+
}
11+
set.Add(root.val);
12+
return FindTarget(root.left, k) || FindTarget(root.right, k);
13+
}
14+
}
15+
16+
// BFS + HashSet
17+
public class Solution {
18+
public bool FindTarget(TreeNode root, int k) {
19+
if (root == null) {
20+
return false;
21+
}
22+
HashSet<int> set = new HashSet<int>();
23+
Queue<TreeNode> q = new Queue<TreeNode>();
24+
q.Enqueue(root);
25+
while (q.Count != 0) {
26+
var node = q.Dequeue();
27+
if (set.Contains(k - node.val)) {
28+
return true;
29+
}
30+
set.Add(node.val);
31+
if (node.left != null) q.Enqueue(node.left);
32+
if (node.right != null) q.Enqueue(node.right);
33+
}
34+
return false;
35+
}
36+
}
37+
38+
// use the feature of BST, flatten it into ordered list.
39+
// then use two pointer.
40+
public class Solution {
41+
public bool FindTarget(TreeNode root, int k) {
42+
if (root == null)
43+
return false;
44+
var list = new List<int>();
45+
TreeToList(root, list);
46+
for (int l = 0, r = list.Count - 1; l < r;) {
47+
int sum = list[l] + list[r];
48+
if (sum == k)
49+
return true;
50+
if (sum < k)
51+
l++;
52+
else
53+
r--;
54+
}
55+
return false;
56+
}
57+
private void TreeToList(TreeNode root, List<int> list) {
58+
if (root == null)
59+
return;
60+
TreeToList(root.left, list);
61+
list.Add(root.val);
62+
TreeToList(root.right, list);
63+
}
64+
}

LeetcodeCShaprDotNetCore/TreeNode.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
namespace LeetcodeCShaprDotNetCore
2+
{
3+
public class TreeNode
4+
{
5+
public int val;
6+
public TreeNode left;
7+
public TreeNode right;
8+
public TreeNode(int x) {
9+
val = x;
10+
}
11+
}
12+
}

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,5 @@ This problem can be solved by typical double pointer technique.
5454
Since the array is already sorted, we can keep two pointers *left* and *right*. let v = nums[*left*] + nums[*right*], if v < target, left++; if v > target, right--; if v == target, then return.
5555

5656
Similar problems:
57-
*1.* Two Sum (use dict for O(1) check time)
57+
*1.* Two Sum (use dict for each item just use almost O(1) check time, so totally O(n) time);
58+
*653.* Two Sum IV - Input is a BST (3 solution to revisit)

0 commit comments

Comments
 (0)