Skip to content

Commit 2255c91

Browse files
authored
Update 1214-two-sum-bsts.js
1 parent 20127ef commit 2255c91

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

1214-two-sum-bsts.js

+43
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,46 @@ const twoSumBSTs = function(root1, root2, target) {
2323
return twoSumBSTs(root1.left, root2, target) || twoSumBSTs(root1, root2.left, target)
2424
}
2525
};
26+
27+
// another
28+
29+
/**
30+
* Definition for a binary tree node.
31+
* function TreeNode(val, left, right) {
32+
* this.val = (val===undefined ? 0 : val)
33+
* this.left = (left===undefined ? null : left)
34+
* this.right = (right===undefined ? null : right)
35+
* }
36+
*/
37+
/**
38+
* @param {TreeNode} root1
39+
* @param {TreeNode} root2
40+
* @param {number} target
41+
* @return {boolean}
42+
*/
43+
const twoSumBSTs = function(root1, root2, target) {
44+
if(root1 == null || root2 == null) return false
45+
const s1 = [], s2 = []
46+
while(true) {
47+
while(root1) {
48+
s1.push(root1)
49+
root1 = root1.left
50+
}
51+
while(root2) {
52+
s2.push(root2)
53+
root2 = root2.right
54+
}
55+
if(s1.length === 0 || s2.length === 0) return false
56+
const t1 = s1[s1.length - 1], t2 = s2[s2.length - 1]
57+
if(t1.val + t2.val === target) return true
58+
if(t1.val + t2.val < target) {
59+
root1 = t1.right
60+
s1.pop()
61+
} else {
62+
root2 = t2.left
63+
s2.pop()
64+
}
65+
66+
}
67+
return false
68+
};

0 commit comments

Comments
 (0)